Why Jquery selector by 'value' not work in case of dynamic change

后端 未结 3 1241
误落风尘
误落风尘 2020-12-19 21:32

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 c

相关标签:
3条回答
  • 2020-12-19 21:51

    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>

    0 讨论(0)
  • 2020-12-19 21:59

    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>

    0 讨论(0)
  • 2020-12-19 22:01

    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>

    0 讨论(0)
提交回复
热议问题