Why Jquery selector by 'value' not work in

2019-02-25 03:34发布

问题:

I'm not sure why jquery selector value not work, Trying to change the value of inputs to "a" but the length not increment, please check the simple example bellow:

$('body').on('input', '.example', function() {
  $('#result').text($('.example[value="a"]').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">

<div id='result'></div>

回答1:

If you are changing value dynamically it wouldn't get selected by attribute selector. You can use filter() instead.

Attribute selector will not check the dom node's value property it only targets the element's attribute

$('body').on('input', '.example', function() {
  $('#result').text($('.example').filter(function() {
    return this.value == 'a'
  }).length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">

<div id='result'></div>


Or you need to manually update the element attribute on input event

$('body').on('input', '.example', function() {
  $(this).attr('value', this.value);
  $('#result').text($('.example[value="a"]').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">

<div id='result'></div>



回答2:

The value attribute describes the default value not the current value. You can't use an attribute selector to solve this problem because you want to deal with current values.

Instead you need to get all your inputs and test their current values one by one.

You can use the filter method for that.

$('body').on('input', '.example', function() {
  $('#result').text(
      $('.example').filter(function (index, element) {
          return ( element.value === "a" );
      }).length
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">

<div id='result'></div>



回答3:

This works:

$('body').on('input', '.example', function () 
{
   $('#result').text( $('.example[value="a"]').val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="example" value="a">
<input type="text" class="example" value="b">
<input type="text" class="example" value="c">

<div id='result'></div>