Home > Article > Web Front-end > Detailed explanation of the similarities and differences in using attr(), prop(), val() to obtain value in jQuery
This article mainly brings you a detailed discussion of the similarities and differences in using attr(), prop(), val() to obtain value in jQuery. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
There are three similar functions in jQuery for obtaining element value: attr(), prop(), val(); let’s compare them.
Sample code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="jquery-2.1.4.js"></script> </head> <body> <input type="text" value="123"/> <button id="btn">click</button> <script> $("#btn").click(function(){ var attr=$("input").attr("value"); var prop=$("input").prop("value"); var val=$("input").val(); console.log(attr); console.log(prop); console.log(val); }) </script> </body>
The code is as shown above, setting the initial value for the input box :123, click the button at this time, the console output is:
123 123 123
Change the value of the input box, at this time the console output:
123 123thgf 123thgf
If we do not set an initial value for the text box, that is, after deleting value="123" and still using the above js code, the corresponding output will be as follows:
undefined
attr() output is undefined, while prop() and val() output is "empty".
After entering the value value: the console output is:
undefined asdasd asdasd
attr() output is still undefined, while prop() and val( ), the actual value is output.
It can be seen that both prop() and val() can get the actual value of the text box, while attr() always gets the attribute value of value in the document structure, which is different from the text box. The actual value is irrelevant and does not change.
Related recommendations:
The difference between .attr() and .data() in jQuery
jQuery .attr() and .removeAttr() methods operate element attributes example_jquery
The above is the detailed content of Detailed explanation of the similarities and differences in using attr(), prop(), val() to obtain value in jQuery. For more information, please follow other related articles on the PHP Chinese website!