Why jquery value selector doesn't work in case of dynamic changes

I'm not sure why the jQuery value selector does not work, trying to change the value of the inputs to "a" , but length does not increase, please check a simple example below:

 $('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> 
+2
source share
3 answers

If you change the value dynamically, it will not be selected using the attribute selector. You can use filter() instead.

The attribute selector will not check the dom node property value , it is only for the element 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 attribute of an element on an 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
source

value attribute describes the default value, not the current value. You cannot 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 check your current values ​​one by one.

You can use the filter method to do this.

 $('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> 
+1
source

It 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> 
-1
source

Source: https://habr.com/ru/post/1237316/


All Articles