jQuery API

.val()

Contents:

.val() Returns: String, Number, Array

Description: Get the current value of the first element in the set of matched elements.

  • version added: 1.0.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:

$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons

Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:

$.valHooks.textarea = {
    get: function( elem ) {
        return elem.value.replace( /\r?\n/g, "\r\n" );
    }
};

Examples:

Example: Get the single value from a single select and an array of values from a multiple select and display their values.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>

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

<script>
    function displayVals() {
      var singleValues = $("#single").val();
      var multipleValues = $("#multiple").val() || [];
      $("p").html("<b>Single:</b> " + 
                  singleValues +
                  " <b>Multiple:</b> " + 
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);
    displayVals();

</script>

</body>
</html>

Demo:

Example: Find the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" value="some text"/>
  <p></p>
<script>
    $("input").keyup(function () {
      var value = $(this).val();
      $("p").text(value);
    }).keyup();
</script>

</body>
</html>

Demo:

.val( value ) Returns: jQuery

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

  • version added: 1.0.val( value )

    valueA string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.

  • version added: 1.4.val( function(index, value) )

    function(index, value)A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

This method is typically used to set the values of form fields.

Passing an array of element values allows matching <input type="checkbox">, <input type="radio"> and <option>s inside of n <select multiple="multiple"> to be selected. In the case of <input type="radio">s that are part of a radio group and <select multiple="multiple"> the other elements will be deselected.

The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:

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

This example appends the string " items" to the text inputs' values.

Examples:

Example: Set the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>
  button { margin:4px; cursor:pointer; }
  input { margin:4px; color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>
    <button>Feed</button>
    <button>the</button>
    <button>Input</button>
  </div>
  <input type="text" value="click a button" />
<script>
    $("button").click(function () {
      var text = $(this).text();
      $("input").val(text);
    });
</script>

</body>
</html>

Demo:

Example: Use the function argument to modify the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <p>Type something and then click or tab out of the input.</p>
  <input type="text" value="type something" />

<script>
  $('input').bind('blur', function() {
    $(this).val(function( i, val ) {
      return val.toUpperCase();
    });
  });
  </script>

</body>
</html>

Demo:

Example: Set a single select, a multiple select, checkboxes and a radio button .

<!DOCTYPE html>
<html>
<head>
  <style>
  body { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <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" name="checkboxname" value="check1"/> check1
  <input type="checkbox" name="checkboxname" value="check2"/> check2
  <input type="radio"  name="r" value="radio1"/> radio1
  <input type="radio"  name="r" value="radio2"/> radio2
<script>
    
    $("#single").val("Single2");
    $("#multiple").val(["Multiple2", "Multiple3"]); 
    $("input").val(["check1","check2", "radio1" ]);

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .val() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .val()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • doitsu-jin

    well, im just wondering about the behaviour of jQuery.val(). in my case i’m using it without any parameters to obtain the value of an input formfield. But everytime called it resets the value of the input after returning it.

  • Anonymous

    I had the same problem and I realized out the next solution:I was using the following code to reset the value of a determinated input in case this was empty:$(“#whatevertheinputis”).focusout(function() { if($(this).val(“”)) { $(this).val(“Default text”); }});It did’nt worked because it reseted the input even if the user wrote some text. But, luckely, I have come with this:$(“#whatevertheinputis”).focusout(function() { if($(this).val() == “”) { $(this).val(“Default text”); }});

  • http://www.sanglt.com/ Lê Thanh Sang

    If using jQuery <=1.3.x you must use this:

    var element = $(this);
    var currentValue = element.val();
    element.focus(function() {
    if(element.val() == currentValue) {
    element.val('');
    }
    }).blur(function() {
    if(element.val() == '') {
    element.val(currentValue);
    }
    });

  • http://openid-provider.appspot.com/rmack005 Ryan

    This page should document the behavior of val() when no elements are matched.

  • http://www.learningjquery.com/ Karl Swedberg

    It behaves the same way any other jQuery method does when no elements are matched. The getter doesn’t run, and the setter returns the (empty) jQuery set.

  • http://openid-provider.appspot.com/rmack005 Ryan

    I realize that. I should have been more specific. I was referring to return value of the getter. If no elements are matched, and the getter doesn’t run, what’s returned? null, empty string, something completely unexpected?

    Similarly, for select elements, if no selection was made, what’s returned?

    It’s not hard to find out, but it’d be nice if it was documented.

  • namata

    val() function will not work for textareas in Opera if you did not set «name» attribute for tag «textarea».

  • http://ifeghali.blogspot.com/ iFeghali

    WARNING! It is no longer possible to set the value of a select by it's text anymore.
    Example:

    <option value=”foo”>bar</option>
    jQuery 1.3.2: you were fine to do $('select').val('bar').change();
    jQuery 1.4.2: you MUST do $('select').val('foo').change();

  • http://profiles.yahoo.com/u/CTONYLMDGINQY5HQCS4G2PGJNI -JD-

    Name 1
    Name 2
    Name 3

    How get the TEXT of Option (example: ‘Name 2′) ?, i tried this code:
    var text = $(‘#selectId’).val();
    its return value ‘value2′ obviously.

  • Name

    $(‘input[type=checkbox]:checked’).val() returns the value of the first checked item, not an array of all checked values.

  • ndmaque

    Drupalers, dont forget you need to watch out for [] in the name, you can't escape them but quote the name part
    $(“input:radio[name='field_type[value]']:checked”).val();

  • David W

    Something along the lines of

    $( ‘#selectid:selected’ ).val( );

    Feel free to correct me ;)

  • David W

    Rats, ignore that. :( I had a surge of stupid.

    Real answer:
    $( ‘#selectid option:selected’ ).text( );

    That will do it :)

  • http://profiles.yahoo.com/u/B5HW7XTENMFKWUSAI63AN2QXZA taitunga

    When the <select> has no options selected this behaves differently in these versions.

    jQuery 1.3.2 returns an empty string
    jQuery 1.4.2 returns null

    Wasted SO much time figuring this one out…

  • Zlati

    then how should i check the value of a selected option?
    if( $(“select#tag_subcat_id option :selected”).val()!=”" || $(“select#tag_subcat_id option ).has(“:selected”){
    do your stuff here…
    }

  • JeffBallweg

    another note on []: if, say you have [] in the name of a select object like so:

    <select id=”foo” multiple=”multiple” name=”foo[]“>
    <option value=”option1″ selected=”selected”>My Selected Option</option>
    <option value=”option2″>My non-selected Option</option>
    <option value=”option3″ selected=”selected”>Another Selected Option</option>
    </select>

    you'd get the array of selected values by:

    var multipleValues = $(“select[name=foo[]]”).val();

    so multipleValues would contain: ['option1','option3']

  • http://cantondog.com CantonDog

    Damn… I need to start reading the comments sooner. This would have saved me some time. Wish they’d update the documentation.

  • http://www.learningjquery.com/ Karl Swedberg

    Try this:
    $(‘input:checkbox:checked’).map(function() {
    return $(this).val();
    }).get();

  • Mike

    Hi Karl, nice solution.

    But it doesn’t work for a check box if you have to specify the name:
    var myData = $(‘input:checkbox[name=myData]:checked’).map(function()
    {
    return $(this).val();
    }).get();

    How do you suggest to specify the name?

  • Mike

    Found it – the solution is this:

    var myData = new Array();
    var i = 0;
    $(“input:checkbox[@name='myData']“).each(
    function()
    {
    if (this.checked)
    {
    myData[i] = this.value;
    i++;
    }
    });

  • Johnny

    But it is not always possible to get 'foo'. You may only have 'bar' available to you. What is the best way to set a select by it's text value?

  • arnab c

    val() method should not be used to set values to input type File, it will not work. just my two cents :-)

  • http://twitter.com/acdameli craig d’amelio

    in jQuery 1.3.2

    jQuery(‘select#ID’).bind(‘change’, handler);
    function handler (e) {
    var thisval = jQuery(this).val(); // expected value
    var byIDval = jQuery(‘#ID’).val(); // empty string
    }

  • JD

    im using .val() to set the initial value of a dropdown when loading a form. in firefox, i have no problem using .val(select_box_index) … but in chrome i need to use the selectbox value (also works in firefox). for various reasons id prefer to use index over value … which is it supposed to be for this?

  • Dan

    In jquery 1.3.2 .val(”) does not clear the input box. Need to use .attr(‘value’, ”) instead.

  • andrea

    $(“select[name=foo\[\]]”).val();

    http://api.jquery.com/category/selectors/

  • guestt

    In the first example used:
    $(“input”).keyup(function () {
    var value = $(this).val();
    $(“p”).text(value);
    }).keyup();

    Why not use:
    $(“input”).keyup(function () {
    var value = $(this).val();
    $(“p”).text(value);
    });

    What's the catch?

  • Cre8vMedia

    I am trying to write a script to clear the default value of an input[type=text] on focus and return it to the default value when it is not changed when it is off focus. I need help here…

  • romont johnson

    $(document).ready(function() {
    $(“input[name=foo]“).focus(function() {
    var foo = $(“input[name=foo]“).val();
    if (foo == “value”)
    {
    $(“input[name=foo]“).val('');
    }
    });

    $(“input[name=foo]“).blur(function() {
    var foo = $(“input[name=foo]“).val();
    if (foo == '')
    {
    $(“input[name=foo]“).val(“value”);
    }
    });
    });

  • Geoffrey

    I have noticed that if the input you want to update value has the same name and id, $(“#id”).val(“new value”); doesn't work properly (at least in Firefx 3.6).

    An alert would tell you the new value but it's not truly added to the input. So make sure your input has a different name and id.

  • xeron

    So that the “p” is initially set to the value of the input (without explicitly coding it above). The .keyup at the end is immediately invoking it.

  • John6630

    I see this in my asp.net page. But how do I set a different name from ID since ASP.Net sets the name automatically to same as the id?

  • Dmik2000

    $(‘#selectId’).val(“value”) will not work is select is hidden (dysplay:none) in IE6.

  • http://twitter.com/dariohead dariohead

    Same thing is happening here. But I think this used to work in the past!

  • Jesse Adler

    It isn’t mentioned but helps a lot.
    $(‘textarea’).val() returns content from …

  • barius

    Thats because # selector uses getDocumentById and it returns only the first found element. If you have multiple same id elements, use $(‘[id=myId]‘) instead of $(‘#myId’)

  • Anonymous

    jQuery 1.4.2 cannot set a through ‘val()’.

    $(“select”).each(function(){
    $(this)
    .before(“<“)
    .after(“>“);
    $(this).siblings(“a.prev,a.next”)
    .click(function(){
    var $sel = $(this).siblings(“select”);
    if ( $(this).hasClass(“prev”) ) var cod = $sel.children(“option[selected]“).prev(“option”).val();
    else var cod = $sel.children(“option[selected]“).next(“option”).val();
    if ( cod ) $sel.val(cod).change();
    });
    });

    This code works fine with 1.3.2, but with 1.4.2 doesn’t work anymore.

  • iGanja

    alright, I'm lost.
    i have a <select> with options like so:<option value=”3″>Hiking</option>when this option is selected, .val() gives me “3″.how do i get “Hiking”?I've tried various forms of .text(), but that gives me the entire list of optionsthere must be something very easy, but I can't seem to find it,thanks</select>

  • http://www.wixiweb.fr Arnolem

    Even in HTML, you can not change the value of input type File.
    To avoid security problems.

  • http://twitter.com/ivanhoe011 Ivan Dilber

    When working with radios that have numerical values, you can't set them with val([2]), you have to pass the value as a string: val(['2']). Yet another jsWTF?

  • Allan Gaunt

    You can just do something like Control.Attributes['name'] = ‘nameString’;

  • Amr

    when i tried the following

    *****
    var array = new Array();
    array[0] = 2;
    array[1] = 3;
    jQuery(“#reg_areaofinterest”).val(array);
    *****
    it did n't work, any idea why?

  • Jamp28

    Passing a id name to a funtion so you can reuse without hardcode the element name.

    I was scratching my head for a while on how to do this.

    For example.

    onclick=”example(this.id);”

    function example(val) {

    str = $('#'+val).val();

    alert( val + ' is: ' + str ); // will return the element name and the val using jquery

    }

    :) cheer

  • deltab

    get() the select element and set its selectedIndex property.

  • go2mobil

    When I use this I can not control the css styles of the output. For example if you keep typing it will run off the screen. I have set padding, margins, width, height, etc. I still cant figure this out.

    Thanks

  • Guest

    I have multiple elements which should respond to input[name=off] and select[name=limitbox] and be updated, but only the first element found is affected by .val, how do i make .val update ALL matching elements?

    $('select[name=limitbox]').change(function() {
    var off = $('input[name=off].prev').val();
    var limit = $('input[name=limit]').val();
    var limitbox = $('select[name=limitbox]').val();
    $('input[name=limit]').val(limitbox);
    var newoff = off*1+limit*1-limitbox;
    $('input[name=off].prev').val(newoff);
    });

  • Luke

    you could probably use the .each() function

  • http://www.ianwalter.net Ian Walter

    The name and ID are the same in grails and I don't know how or if I can change it. None of the other jQuery manipulators I've tried have a problem with this. Why does val!?

  • Girish24041984

    I am using this. but it's not working.

    var array = result.sCitizenship.split(','); //array[0]=1,array[1]=2
    $(“#citizenship”).val(array);

    please help

  • http://pulse.yahoo.com/_T6Z5PVE2Q3DMY4MPWBVW5W4UZI girish

    i am just a beginner in jquery and having this problem….

    var array = result.sCitizenship.split(','); //array[0]= 1, array[1]=2
    $(“#citizenship”).val(array);

    it is not selecting the multiple values in drop down.

  • http://twitter.com/chadhikes Chad Killingsworth

    In the Raw XML, the “value” parameter is listed as type “string”. Wouldn't a number work here as well?

  • http://www.learningjquery.com/ Karl Swedberg

    Well, I suppose it can take a number, but only because that number is automatically converted to a string.

  • Jason

    In the event that you have option values, how can return the text that is with the option tags?

    Ex. <option>Hello</option>
    This would select Hello according to the above jQuery.

    But if I had something like:
    Ex. <option value=”1″>Hello</option>

    It would return 1 instead of Hello. Any ideas on how to return the text within the option tags instead?

  • Jason

    Nevermind, I found a solution. If anyone else has the same question, the solution was found here:
    http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_get_the_text_value_of_a_selected_option.3F

    under the heading: “How do I get the text value of a selected option?”

    $('#myselect option:selected').text()

  • wraithguard01

    To be more specific, $('textarea').html() returns what was originally set in between the textarea tags. $('textarea').val() returns what is currently in the textarea. So, for the following example:
    <textarea>Original Text</textarea>
    at first would return “Original Text” for both .val() and .html(), but if the user changes the text to “New Text” in the textarea, then .val() returns “New Text”, and .html() still returns “Original Text”.

    Furthermore, if you call $('textarea').html(“New Text”), then .val() and .html() will return “New Text”. However, if you call $('textarea').val(“Newer Text”), then .val() will return “Newer Text”, and .html() will return “New Text”.

    This caused much confusion for me at first, so I hope this helps someone else.

  • Markus

    It seems that setting values for option menus (type=”select”) with val() doesn't work with Opera

  • http://twitter.com/cre8vmedia Kassem, Adedoyin O.

    I have two select menus and a checkbox.
    SELECT A & SELECT B
    how do i show SELECT A and hide SELECT B if checkbox is checked,
    and hide SELECT A, but show SELECT B if checkbox is unchecked.

    This is really urgent!

  • http://twitter.com/cre8vmedia Kassem, Adedoyin O.

    I have two select menus and a checkbox.
    SELECT A & SELECT B
    how do i show SELECT A and hide SELECT B if checkbox is checked,
    and hide SELECT A, but show SELECT B if checkbox is unchecked.

    This is really urgent!

  • http://twitter.com/cre8vmedia Kassem, Adedoyin O.

    I have two select menus and a checkbox.
    SELECT A & SELECT B
    how do i show SELECT A and hide SELECT B if checkbox is checked,
    and hide SELECT A, but show SELECT B if checkbox is unchecked.

    This is really urgent!

  • http://twitter.com/cre8vmedia Kassem, Adedoyin O.

    I have two select menus and a checkbox.
    SELECT A & SELECT B
    how do i show SELECT A and hide SELECT B if checkbox is checked,
    and hide SELECT A, but show SELECT B if checkbox is unchecked.

    This is really urgent!

  • Ryany

    Good examples. can anybody teach me how to change a value of a radio button same as the input text in the textbox?

  • Ryan

    never mind :D i got it :D

  • quiff

    Ive found that if trying to set the checked radio button using variables and strings, then it must be something like this

    $(“input”).val(["string"+variable+"string"]);

    not sure why the square brackets are needed but it had me scratching my head for a while.

  • http://powerlord.livejournal.com/ R. Bemrose

    An important note here: .val(value) on an HTML select element will not fire any attached change events.

  • Pilgrim_yang

    but if you first input.focus(); then $.val('abcd'); a change event will be fired.

  • Xbn-fiber

    $('input:radio[name=info[type]]:checked').val()

    This code is wrong, who can help me?

  • http://www.mobilephones.com.pk Mobile Phones Prices

    Always love JQuery

  • http://www.mobilephones.com.pk Mobile Phones Prices

    Always love JQuery

  • Fabio

    jQuery 1.4.4 breaks .val() when trying to set the selected option of a select.

    It works ok in jQuery 1.4.3 and earlier versions.

  • Dsfsfa

    aa

  • http://pulse.yahoo.com/_VXZLJQQOL3KNWJA77XBHGVNNYY nonone

    You need the square brackets because setting a radio button requires an array.

  • Brandon K

    Thanks for the heads up. I've noticed the same, a workaround: $(select).val(value).trigger('change');

  • keyrusAndre

    Hello Girish20041984! Did you find the solution? I have the same issue and I don´t know how to fix it!…
    Does anyone know why if I try to set multiple values through an array variable it does´nt work?

    Girish20041984 I´ll take your example:

    var array = result.sCitizenship.split(','); //array[0]= 1, array[1]=2
    $(“#citizenship”).val(array);

    it is not selecting the multiple values in drop down.

    Thank you!

  • Paul

    I notied that .val('') (two single quotes) clears the select list of options, whereas .val(“”) (two double quotes) sets the selection to the option where value=”" this was in jQuery 1.3.2 — but this could be the case for you as well…

  • Gediminas

    for the jQuery 1.4.4, .val( true ) for the checkbox type input sets it attribute value=true, not checked=true, leaving checkbox unchecked

  • http://www.facebook.com/paulslater19 Paul Slater

    I was having this issue too. I finally figured out that it was because I had duplicated an element that had an id — even though I wasn't accessing the element by id. I removed the id and no problems