.val()
methodThe .val()
method in jQuery is used to get/set the value of form element.
.val()
method Syntax.val([value|function]) // That is .val() .val(value) .val(function)
Parameter | Type | Description |
---|---|---|
value |
String,Number,Array | the value to set for matched elements |
funtion(index, oldValue) |
Function | a function returning the value to set. index is the position of the element in the set.(based 0) oldValue is old value, you can process it in the function. |
.val()
Get the current value of the first element
in the set of matched elements.
// Get the value from a dropdown select directly $( "select#foo" ).val(); // Get the value from the selected option in a dropdown $( "select#foo option:checked" ).val(); // Get the value from a checked checkbox $( "input[type=checkbox][name=bar]:checked" ).val(); // Get the value from a set of radio buttons $( "input[type=radio][name=baz]:checked" ).val(); // Get the value from a text input $("input").val();
.val(value)
Set the value of each element in the set of matched elements.
Set the value of the text input box.
$("input").val("newValue!");
Set the single value for a single select and an array of values for a multiple select,set checkbox and radio button
HTML Code:
<select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" value="check1"/> check1 <input type="checkbox" value="check2"/> check2 <input type="radio" value="radio1"/> radio1 <input type="radio" value="radio2"/> radio2
jQuery Code:
$("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check2", "radio1"]);
.val(value,function(index,oldValue))
The function would return the value to set.the index
is current element's index and oldValue
its current value before setting.
change the values of text inputs with a "tags" class.
$('input:text.tags').val(function(index,oldValue) { return this.value + ' index:' + index + ' oldValue:' + oldValue; });