如果主类文本框值与用户匹配,则下面的代码添加为yes,但我想将master与用户类进行比较,并在div中打印数字计数结果,输入用户类具有相同的重复次数作为主人的价值。
HTML:
<input class="master" value="1">
<input class="user" value="1">
<input class="user" value="1">
<input class="user" value="0">
<input class="user" value="0">
<div id="result_count"></div>
使用Javascript:
$(function() {
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
$('input.user').val(fn); // loop and replace text for each user input
});
答案 0 :(得分:1)
这应该可以胜任:http://codepen.io/zvona/pen/qOqKJe?editors=101
var masterValue = $('.master').val();
var $userInputs = $('.user');
var resultCount = $userInputs.filter(function(i, input) {
return $(input).val() === masterValue;
});
$('#result_count').text(resultCount.length);
答案 1 :(得分:1)
您应该根据主输入的值使用属性选择器:
$(function() {
var master = $('input.master').val(); // get the master value
var userInputs = $('input.user');
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
userInputs.val(fn); // loop and replace text for each user input
// get inputs who has the same value as "master"
var inputs = userInputs.filter( 'input[value="'+ master +'"]' )
// Print the number of matches
console.log( inputs.length )
});
答案 2 :(得分:1)
var same = $('input.user').filter(function( index ) {
return ($(this).val() == $('.master').val());
})
console.log(same.length);
$('#result_count').text(same.length);
https://gist.github.com/TonyMtz/d75101d9bdf764c890ef
demo了解更多信息
答案 3 :(得分:1)
$(function() {
var count=0;
var master = $('input.master').get(0).value; // get the master value
var fn = function() {
return this.value === master ? "yes" : "no";//if current text-box matches master,then yes else no
};
$('input.user').val(fn);
$(".user").each(function() {
if($(this).val()==master ){
++count;
}
});
$('#result_count').val(count);
});