我有几组问题,每组问题包含2个输入字段。
<!--Question Set-->
<tr class="options_row">
<td>
<img src="images/top_bullet.gif" alt="bullet" />
I will only be satisfied with a usually high standard of living </td>
<td width="5%">
<input name="score[]" type="text" class="score num" title="1" maxlength="1" />
</td>
</tr>
<tr class="options_row">
<td>
<img src="images/top_bullet.gif" alt="bullet" />
I wish to have considerable influence over other people. </td>
<td width="5%">
<input name="score[]" type="text" class="score num" title="2" maxlength="1" />
</td>
</tr>
现在我需要验证两组输入值
例如
- &gt;问题集1 - &gt; Input_1 + Input_2&gt; = 3
- &gt;问题集1 - &gt; Input_1 + Input_2&lt; = 3
我尝试过使用closest
功能,但它有效。
var score_val = $(this).closest('.score');
感谢。
答案 0 :(得分:1)
您可以为每个集添加额外的数据属性:
<input name="score[]" type="text" data-set="1" class="score num" title="1" maxlength="1" />
然后迭代那些:
var questionSet = {}, i = 0;
$('.score attr["data-set"]').each(function(){
i++;
questionSet[$(this).data('set') = {
i: $(this).value()
};
i = (i > 2)? 0 : i;
});
这将返回如下对象:
questionSet = {
1: {
1: "value1",
2: "value2"
},
2: {
1: "value1",
2: "value2"
}
}
现在你可以迭代这个对象了:
for(x in questionSet){
if (x[1] + x[2] >= 3) {
// do something...
} else {
// do something else...
}
}
答案 1 :(得分:0)
毕竟这就是我想出来的
(function($) {
$.fn.calVal = function(params) {
params = $.extend({value:3,message:'The combined value should not be greater than or less than 3'});
//Get the current node
var $t = $(this);
//If the node out of focus
$t.blur(function() {
//get the current group
var data_set = $(this).attr('data-set');
//the actual sum
var total = 0;
//loop through the current node to get the group of its own
$t.each(function(){
//get the group of sellected node
var cur_data_set = $(this).attr('data-set');
//if any matching group of the current node
if(cur_data_set==data_set)
{
//total the value of each selected node group
total += parseFloat($(this).val());
}
});
//Validate the group value and return the result
if(total>params.value)
{
alert(params.message);
$(this).val('');
}else if(total<params.value)
{
alert(params.message);
$(this).val('');
}
});
// allow jQuery chaining
return this;
};
})(jQuery);
逻辑可能有点蹩脚,但它对我有用;)
感谢Mr.AvL展示了正确的道路:)