JavaScript
Article
By Sam Deering

jQuery .val() works 2 ways on select inputs

By Sam Deering

Quicky. It might be handy if you didn’t know that .val() function works 2 ways on select boxes to set the value of the drop down.

--ADVERTISEMENT--

HTML

Way 1

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

Way 2

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

Other methods

$("#my-Select option[text='Option1']").attr("selected","selected");

$('#my-Select option[value="1"]').attr("selected","selected") ; or $('#my-Select option:nth(2)').attr("selected","selected");

Also see: jQuery Loop Select Options

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account