Shaik
Shaik

Reputation: 930

Javascript Count number of time same value repeated in the textbox(s)

The below code add as yes if the master class text box value matches with the user but i want to compare the master with the user class and print the number count result in a div of how many input user class have the same repeated value of as master has.

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
});

Upvotes: 3

Views: 1350

Answers (4)

guradio
guradio

Reputation: 15555

var same = $('input.user').filter(function( index ) {
    return ($(this).val() == $('.master').val());
  })
console.log(same.length);
$('#result_count').text(same.length);

demo

Documentation for more information

Upvotes: 1

Vibhesh Kaul
Vibhesh Kaul

Reputation: 2613

$(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);
});

Upvotes: 1

elad.chen
elad.chen

Reputation: 2425

You should use the attribute selector based on the master input's value:

$(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 )
});

An example: http://jsfiddle.net/gjangztm/

Upvotes: 1

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

This should do the job: 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);

Upvotes: 1

Related Questions