简体   繁体   中英

How to set the value of the option select?

Noob question I just want to set a value of an option in select tag via jQuery I'm doing this:

HTML:

<select class="mySelect">
  <option value="">1</option>
  <option value="">2</option>
  <option value="">3</option>
  <option value="">4</option>
</select>

JS:

$('select.mySelect:first-child').val("test");

This should set the value of the first option to "test", but it doesn't. What am I doing wrong here?

Try this:

$('select.mySelect :first-child').val("test");
// add a space ---^

Your selector was looking for a select element that is a first child, not the first child of a select element.

You would also need to ensure that that JS is executed after the element in question is parsed, so include it in a script element that appears after the select (putting your script just before the closing </body> tag is a common convention) and/or wrap it in a document ready handler.

$('select.mySelect option:eq(0)').attr('value', 'myvalue');

When you use val() to set a value to a select, jQuery searches for the the <option> and marks it as the selected choice. What you want to do is alter its 'value' attribute, which is what Adrian has done

$('select.mySelect option:eq(0)').attr('value', 'myvalue');

You can controll witch child to add value by .eq() like this:

$('select.mySelect option').eq(0).val("test");

Above code will select all options and filter through them to find the very first option. change it to eq(1) for the second option and so on.

http://jsfiddle.net/Zy974/

ALSO

press F12 on chrome and go to Console tab. Do you see any error there?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM