使用JQuery比较输入字段 [英] Comparing input fields using JQuery
问题描述
我目前有一个输入表格.每个输入类别有两个条目,如下所示:
I currently have an input form. There are two entries for each input class as follows:
<form>
<input type="text" name="firstname_a" class="firstname" disabled="disabled" />
<input type="text" name="firstname_b" class="firstname" />
<input type="text" name="surname_a" class="surname" disabled="disabled" />
<input type="text" name="surname_b" class="surname" />
<input type="submit" value="submit" />
</form>
提交时,我希望JQuery检查值a是否与值b相匹配(最终用户输入了值a,而为审核公司工作的外包工人输入了值b).该表格最多可包含470个输入字段,这些字段取决于进行审核的类型而存储在数据库中.因此,我不想键入470次!:
On submission I want JQuery to check whether or not value a matches value b (value a has been entered by the end user, value b has been entered by a outworker working for a vetting company). The form could have upto 470 input fields, these are stored in a database dependant upon the type of vetting being carried out. I don't, therefore, want to have to type out 470 times!:
if($('input["name=firstname_a"]').val() == $('input["name=firstname_a"]').val())
{
// do something
}
else
{
// do something else
}
相反,我想找到一种动态的方式来执行此操作,可能使用serializeArray()函数,但是我很挣扎!所有或任何帮助将不胜感激.
Rather I would like to find a dynamic way to do this, possibly using the serializeArray() function, but I'm struggling! All or any help would be greatly appreciated.
推荐答案
您可以循环浏览以_a
结尾的.each
输入,并与_b
对应的内容进行比较:
You can cycle through .each
input ending in _a
and do the comparison with its _b
counterpart:
$('#target').submit( function() {
// Iterate over each input with name ending in _a
$('input[name$="_a"]').each( function() {
// Get the base name by removing _a
var name = $(this).attr('name').replace(/_a$/, '');
// Compare _a to _b
if( $('input[name="'+name+'_a"]').val() != $('input[name="'+name+'_b"]').val()) {
alert(name+" field does not match!");
}
});
return false;
});
示例:
http://jsfiddle.net/jtbowden/yqMGG/
以下是所有不匹配项都会保存并在最后发出警报的版本:
Here is a version where all mismatches are saved and alerted at the end:
http://jsfiddle.net/jtbowden/amsJj/
或突出显示错误的版本:
Or a version that highlights the errors:
http://jsfiddle.net/jtbowden/V8xJX/
这篇关于使用JQuery比较输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!