Home  >  Article  >  Web Front-end  >  Detailed explanation of the similarities and differences in using attr(), prop(), val() to obtain value in jQuery

Detailed explanation of the similarities and differences in using attr(), prop(), val() to obtain value in jQuery

小云云
小云云Original
2018-01-17 11:26:301918browse

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’s attr( ) and prop()

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!

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