3

Does anyone know how to set the first option value of a select using jquery? For example i have the following select tag.

<select id = "my-id">
    <option value=""></option>
</select>

I want to set the value. So far I have unsuccessfully attempted the following.

$("select#my-id").first().val("hello world");

document.getElementById('my-id').value="hello world";

$("select#my-id option")
         .each(function() {
                 this.text = query.eguide;
                 this.value =query.eguide;});
sirFunkenstine
  • 8,135
  • 6
  • 40
  • 57

2 Answers2

6
$("#my-id option:first").attr("value", "blahblah");

or (thanks to @Tom)

$("#my-id option:first").val("blahblah");

This will set the val attribute to blahblah. Obviously changing blahblah to whatever you need.

ntzm
  • 4,663
  • 2
  • 31
  • 35
  • 1
    Does one have to use `attr("value", ...)` or would `val(...)` also work? – Tom May 12 '14 at 17:46
  • 1
    Just tested it now - It seems to do the same with, I will update the answer. You can see for yourself here: http://jsfiddle.net/N5h8F/ – ntzm May 12 '14 at 19:11
2

And a solution with plain js you can try:

document.getElementById("my-id").options[0].value="TEST";

DEMO

laaposto
  • 11,835
  • 15
  • 54
  • 71