Home  >  Article  >  Web Front-end  >  What is the difference between attr and val in jquery

What is the difference between attr and val in jquery

WBOY
WBOYOriginal
2022-05-09 11:21:132725browse

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.

What is the difference between attr and val in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

What is the difference between attr and val in jquery

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

What is the difference between attr and val in jquery

Then use val() and attr respectively ("value") prints out

console.log("这个是val: "+$("#jibengongzi").val());
console.log("这个是attr:"+$("#jibengongzi").attr("value"));

What is the difference between attr and val in jquery

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

What is the difference between attr and val in jquery

then use attr to assign a value

$("#jibengongzi").attr("value",ruleForm.jibengongzi);

What is the difference between attr and val in jquery

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn