I have a very simple example jsfiddle:
HTML:
<input type="text"/>
<input type="text" value="aaa"/>
JS:
$("input:first").val("aaa");
alert($("input[value='aaa']").length);
Why Chrome and IE returns different results? Why jQuery in Chrome not recognize the “value” when it was set using jQuery?
How I can solve it? I need that Chrome will return exactly the same result as IE.
EDIT: I unaccepted my answer, because after thinking about it little bit, I still not understand some things (maybe I am wrong regarding several parts):
1) As I know, the text displayed in textbox by browser, should always be in “value” attribute, because if I submit the form, the “values” displayed in textboxes and other input fields are submitted to server (if they are not disabled).
2) So if displayed text in textbox should be stored in “value” in order to be submitted, then it’s natural for me if $("input[type='text']").val("aaa") would assign the text “aaa” to “value” attribute, because it may be submitted later. If so, why $("input[value='aaa']") not pick it up?
3) Some other thing….when I not use “val” method of jQuery, and instead type the text directly to textbox, then it not goes to “value” attribute to? I made another example, where I not use “val” to assign text to textbox. I type it directly in textbox, and then $("input[value='aaa']") not pick it up again.
It’s very very strange for me…i understand the difference between the properties and attributes, but due to nature of HTML forms, I not understand why “val” not assigns the value to attribute, and when typing in directly, it not goes to “value” attribute to.
BTW: In http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/ i found the following:
Neither .attr() nor .prop() should be used for getting/setting value.
Use the .val() method instead (although using .attr(“value”,
“somevalue”) will continue to work, as it did before 1.6).
They say that “val” should set the attribute…or my English not allows me to understand it right?
Please explain me 🙂
I think it is because
.valsets the property on theinput. Then using the[value="aaa"]is looking at the attributes of theinput, which hadn’t actually changed. If you change how you usejQueryto set the value of the input to:$("input:first").attr("value", "aaa");And then check the length, you’ll get the results you’re expecting.
Fiddle: http://jsfiddle.net/gromer/ZnbpE/
Difference between properties and attributes:
http://blog.jquery.com/2011/05/12/jquery-1-6-1-released