Home > Article > Web Front-end > What is the difference between attr and val in jquery
Difference: 1. The val method can obtain the manually entered value, but the attr method cannot; 2. If you use val to assign a value, you can use the val method to obtain it, but the attr method cannot obtain it; 3. Use When attr is assigned a value, if the input value is manually changed, val can obtain the latest value, while attr still obtains the initial value.
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
Let me talk about the conclusion first and then post the code analysis. The differences are as follows:
1.val can get the manually entered value, but attr cannot Yes
2. Use val to assign value, val can get the value, attr cannot
3.Use attr to assign value, both val and attr can get the value. If you change the input value manually, val can Get the latest value. What attr reads is still the value assigned to attr at the beginning.
First manually enter a number
Then use val() and attr respectively ("value") prints out
console.log("这个是val: "+$("#jibengongzi").val()); console.log("这个是attr:"+$("#jibengongzi").attr("value"));
It can be seen that attr("value") cannot obtain the manually entered value
Next use val( ) to assign a value (ruleForm.jibengongzi is a number)
$("#jibengongzi").val(ruleForm.jibengongzi);
Then print it out
then use attr to assign a value
$("#jibengongzi").attr("value",ruleForm.jibengongzi);
In addition, there is a bug in attr during use, which prevents me from using js to assign values to the input box. I don’t know the specific reason. It will be fine if I use val instead. This article is only a personal learning record. If you have any questions, please point them out and learn and progress together
Recommended related video tutorials:jQuery video tutorial
The above is the detailed content of What is the difference between attr and val in jquery. For more information, please follow other related articles on the PHP Chinese website!