The jQuery Val method is the most used method which either returns or sets the value attribute of the selected elements.
For Returning Value – It returns the first matched element attribute’s value.
For Setting Value – It sets the value of all matched elements.
The .val() method has 3 syntaxes.
1. For Returning Value
$(selector).val()
2. For Setting Value
$(selector).val("Hello")
3. For Setting Value through a Function
$(selector).val(function(index,currentvalue))
I have one textbox and a button. On the button click the value of the textbox is set as ‘Hi’.
This code is shown below.
<input type="text" id="text1" value="Welcome" />
<button id="button1">Set 'Hi'</button>
$("#button1").click(function (e) {
$("#text1").val("Hi");
});
This time my text box has initial value as ‘jQuery’, I will append ‘Hi’ to this value by using .val() method.
The button click event will set value of textbox as ‘jQuery Hi’.
<input type="text" id="text2" value="jQuery" />
<button id="button2">Set 'jQuery Hi'</button>
$("#button2").click(function (e) {
$("#text2").val(function (index, currentvalue) {
return currentvalue + " Hi";
});
});
The below code alerts the value of the textbox on the button click event.
<input type="text" id="text3" value="Hello Coder!" />
<button id="button3">Get Value</button>
$("#button3").click(function (e) {
alert($("#text3").val());
});
Just like textboxes, the jQuery Val method can also get the selected value of drop downs.
<select id="select1">
<option value="First">First</option>
<option value="Second">Second</option>
<option value="Third">Third</option>
</select>
<button id="button4">Get Value</button>
$("#button4").click(function (e) {
alert($("#select1").val());
});
In the above code you select the second value of drop down, and then click the button.
The alert box will show Second.
I have 2 checkboxes and a button. One the button’s click both the checkboxes will be checked.
<input type="checkbox" value="check1"> check1
<input type="checkbox" value="check2"> check2
<button id="button5">Set</button>
$("#button5").click(function (e) {
$("input[type='checkbox']").val(["check1", "check2"])
});
Note that in the above code I have passed multiple value to the jQuery .val() method. Also use the below download link: