JQuery.val (...) does not change the DOM?

I'll just start by presenting code that doesn't behave as it should. Since it is very simple, he must speak for himself.

HTML:

<input id="bla"></input> <input id="blub"></input> 

JavaScript:

 jQuery('#bla').attr({'value': 'a'}); jQuery('input[value="a"]').val('s'); jQuery('#blub').val('d'); jQuery('input[value="d"]').val('f'); 

jsFiddle: http://jsfiddle.net/5dww7/

Problem: jQuery('input[value="d"]') - undefined

This is mistake? Firebug actually says that β€œvalue” exists - maybe a selector problem?

+4
source share
2 answers

When you use val , you change the value property. When you use attr , you change the attribute.

When you use an attribute selector to select an element, it will only work if the attribute is present.

If you need to select elements based on the value of their value property, you can use filter :

 $("input").filter(function() { return this.value === "whatever"; //Accesses the value property }); 
+5
source

The jQuery .val() method changes the value property, not the value attribute. The attribute is equal to the selector selected by the attribute, and not by the property (which is executed by the browser css engine in modern browsers).

+6
source

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


All Articles