Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get and set form element values with jQuery?
To get a form value with jQuery, you need to use the val() function. To set a form value with jQuery, you need to use the val() function, but pass it a new value as a parameter.
The val() method is versatile and works with various form elements including text inputs, radio buttons, checkboxes, and select dropdowns. When called without parameters, it retrieves the current value. When called with a parameter, it sets the value.
Syntax
Here's the basic syntax for getting and setting form values ?
// Get value
var value = $("#elementId").val();
// Set value
$("#elementId").val("new value");
Example
You can try to run the following code to learn how to get and set form element values with jQuery ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#buttonSet").click(function () {
$("#txtBox").val("Amit");
$("input:radio[value='male']").prop('checked', true);
$("#buttonGet").removeAttr('disabled');
});
$("#buttonGet").click(function () {
$("#result").html(
"Name: " + $("#txtBox").val() + "<br/>" +
"Gender: " + $("input:radio[name=rd]:checked").val()
);
});
});
</script>
</head>
<body>
Name <br />
<input id="txtBox" type="text" />
<br /><br />
Gender <br />
<input type="radio" name="rd" value="male"/> Male
<input type="radio" name="rd" value="female"/> Female
<br /><br />
<input id="buttonSet" type="button" value="Set Values" />
<input id="buttonGet" type="button" value="Get Values" disabled="disabled" />
<p id="result"></p>
</body>
</html>
The output of the above code demonstrates how jQuery can dynamically set form values and retrieve them. When you click "Set Values", it populates the text field with "Amit" and selects the "Male" radio button. The "Get Values" button then displays the current form values.
Conclusion
The jQuery val() method provides a simple and consistent way to get and set form element values across different input types. This makes form manipulation straightforward and efficient in web applications.
