pillarOfLight
pillarOfLight

Reputation: 8992

setting the value of a select form with jquery

so apparently you have the following

<select>
    <option value="0">One</option>
    <option value="1">Two</option>
</select>

$('select').val('1'); // selects "Two"
$('select').val('Two'); // also selects "Two"

but what if you have

   <select>
        <option value="0">1</option>
        <option value="1">0</option>
    </select>

And I want to set the value...of the form...how can I tell jquery to specifically use the value field or specifically the text in between the option tag...

Upvotes: 0

Views: 5764

Answers (3)

HAROONMIND
HAROONMIND

Reputation: 123

Just select the option based on the value (with the attribute selector) and set the selected attribute like this Simply no Headace :)

By Value

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

https://jsfiddle.net/haroonmind/quemz47o/1/

Upvotes: 0

aziz punjani
aziz punjani

Reputation: 25796

​$('select').find('option[value="1"]')​​​​​​​​​​​​​​​​​.attr('selected', true );  

Upvotes: 3

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

Just select the option based on the value (with the attribute selector) and set the selected attribute like this:

var value = "1"; // Set the value that you want to select
$("select option[value=" + value + "]")​​.attr("selected","selected")​​;​

http://jsfiddle.net/VU9BC/

Upvotes: 2

Related Questions