jQuery val() returns or sets the value attribute of the selected elements.
Below the syntax of jquery val() method
.val();
.val(content);
.val(function (index, currentvalue));
Parameters of jQuery val()
Parameter |
Description |
content |
It is mandatory parameter. It is used specify the value of the attribute. |
function(index,currentvalue) |
It is an optional parameter. It specifies the function that returns the value to set.
- index - It returns the index position of the element in the set.
- currentvalue - It returns the current value attribute of selected elements.
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery val()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
$("#name").val("nexladder")
});
});
</script>
</head>
<body>
<input type="text" name="name" id="name" /><br /><br />
<button style="margin:0 0 10px 0" class="btn" id="button">Set the value of input field</button><br />
</body>
</html>
Below the another example of val() method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery val()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#language").change(function() {
var val = $(this).val();
$("#response").html(val);
});
});
</script>
</head>
<body>
<select name="language" id="language" class="form-control" style="width:40%">
<option value=""> -- Select --</option>
<option value="Php">Php</option>
<option value="Html">Html</option>
<option value="Css">Css</option>
<option value="JavaScript">JavaScript</option>
<option value="Jquery">Jquery</option>
</select><br />
<span id="response"></span><br />
</body>
</html>