Netorica
Netorica

Reputation: 19347

Set the select box to its default selected index using jQuery

Ok, I have a select box

<select id="txtPriority" style="color:#008000;">
    <option value="0" style="color:#0000FF;">Low</option>
    <option value="1" selected="selected" style="color:#008000;">Normal</option>
    <option value="2" style="color:#B22222;">Critical</option>
</select>

Now with that select box, I want to create a button that when clicked would return back the select box's selected item to the <option> that has selected="selected". Now is this possible with a simple jQuery code?

Upvotes: 2

Views: 6033

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

If I well understood there's no need to use jQuery: just wrap that select in a form and use a reset button (see http://jsfiddle.net/vwqVJ/5/)

<form ...>
    <select id="txtPriority" style="color:#008000;">
    ...
    </select>

    <button type="reset">Restore choice</button>
</form>

In this way when you change the select you can always turn back to the initial state

If you need instead to use jQuery just invoke the reset method on the form element, like

$('form').get(0).reset()

otherwise, if you have no form at all (but you really should use it) just use

$('#txtPriority').val($('#txtPriority option[selected]').val())

Upvotes: 7

Thulasiram
Thulasiram

Reputation: 8552

$('#txtPriority').val('1');  //try this

Upvotes: -1

bitoshi.n
bitoshi.n

Reputation: 2318

I don't know the meaning of 'a button that would return back the select box's selected item' But

$("select#txtPriority option:selected").first();

Will give you selected option item.

Upvotes: 0

Related Questions