jQuery Tutorial Tutorials - jQuery .val() method

jQuery .val() method

The .val() method in jQuery is used to get/set the value of form element.

jQuery .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.

example

// 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();

Try it

.val(value)

Set the value of each element in the set of matched elements.

example1

Set the value of the text input box.

$("input").val("newValue!");

example2

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"]);

Try it

.val(value,function(index,oldValue))

The function would return the value to set.the index is current element's index and oldValueits current value before setting.

example

change the values of text inputs with a "tags" class.

$('input:text.tags').val(function(index,oldValue) {
    return this.value + ' index:' + index + ' oldValue:' + oldValue;
});

Try it

Date:2019-08-19 15:52:13 From:www.Lautturi.com author:Lautturi