我想寫一些驗證作爲我的頁面的一部分,確保如果文本框有一些必需的文本,它將禁用該按鈕,如果它不存在。如何使用jQuery檢查文本框中的所有元素?
我有這方面的工作完全使用下面的jQuery代碼:
<script>
$(document).on("ready", function() {
$('input[type="text"]').on('blur', function() {
var $required = $(this).next().val();
var $image = $(this).parent().next().children('img');
var $errors = $('img:visible').length;
if (($(this).val().indexOf($required) == -1) && ($(this).val() != '')) {
$image.show();
$("#submit").prop("disabled", true);
} else {
$image.hide();
//Manually subtract from error otherwise it doesnt subtract until the next focus change
$errors--;
if ($errors == 0)
$("#submit").prop("disabled", false);
}
});
});
</script>
當文本框需要兩個值出現問題。它們作爲逗號分隔的字符串存儲在隱藏的輸入中。我如何檢查兩者都存在?只要他們都在那裏,他們可以以任何順序在那裏。我知道我可以使用.split(',')來獲取並排列和測試它們,但那是我粘在的部分。
我已經嘗試使用.inArray()和.each(),但只是無法得到它的任何地方。
我試圖設置一個小提琴,但無法讓它工作。
下面是HTML作爲一個MVC項目的縮減版本,所以大部分是由模型等填充
HTML
<table width="100%" border="1px solid">
<tr>
<th>Source Text</th>
<th>Translation</th>
</tr>
<tr>
<td>Some text here</td>
<td><input type="Text"><input type="hidden" value="Some"></td>
<td><img id="cross" src="../cross.png" class="jq-cross hid" alt="error" /></td>
</tr>
<tr>
<td>Some text here</td>
<td><input type="Text"><input type="hidden" value="Some,Here"></td>
<td><img id="cross" src="" class="jq-cross hid" alt="error" /></td>
</tr>
<tr><td colspan="3"><button id="submit" type="submit">Update Translations</button> </td></tr>
</table>
任何幫助,您可以給我會非常感謝。希望我在這裏提供了足夠的信息。
在此先感謝
如果你只是標記像'所需的輸入字段很多你的邏輯將被簡化<所需的輸入>'(或者甚至只是''在HTML 5中),然後將它用於你的事件處理程序選擇器,比如'('input'[data-required]:text')。on('blur',fn)'。 – 2012-07-17 15:39:02