Example of val of method usage in jQuery

  • 2020-05-09 18:07:59
  • OfStack

This article illustrates the use of the val() method in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

This method sets or gets the value of the value attribute of the matching element.

Only elements with the value attribute can use this method. For example, the input element can use this method, while the div element cannot.

Usage:

Use 1:

This method returns the value attribute value of the first matched element with no arguments. Such as:

$("input").val()

The above code is to get the value attribute value of the first input element.
Example code:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title>val() function - The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($("input").val());
  })
})
</script>
</head>
<body>
<div>
  <ul>
    <li>
      <input type="text" value=" Please enter a user name " />
    </li>
  </ul>
</div>
<button> Click to view </button>
</body>
</html>

Use 2:

This method takes a parameter to set the attribute values of all matched elements. Such as:

$("input").val(" This is the test script ")

The above code sets the value attribute value of all input elements to "this is the test script."
Example:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title>val() function - The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("input").val(" This is the test script ");
  })
})
</script>
</head>
<body>
<div>
  <ul>
    <li>
      <input type="text" value=" Please enter a user name " />
    </li>
  </ul>
</div>
<button> Click to view </button>
</body>
</html>

Hope that this article described the jQuery programming help.


Related articles: