Michael De Keyser
Michael De Keyser

Reputation: 797

jQuery select a specific option in <select> tag

I'm struggling with a little script that shouldn't be that hard... I'm catching the change event of a select tag and proceed to some ajax stuff. At the end I process the response of the ajax call and under some condition I'm trying to "rollback" the user's action.+

So he's selecting an option, option is sent to server via ajax, server says "no way you can't do that", I display a little alert message telling the user he's not smart and then try to reselect the default option which is the first one, a blank.

Here's the DOM part:

<select class="closedStatus">
    <option data-requestid="2" value="-1">&nbsp;</option>
    <option data-requestid="2" value="3">yes</option>
</select>

So, I'd like to set the selected option back to the first one, with value="-1".
But so far no luck... Here's my code:

$('.closedStatus').val('-1');

I found this in another post but this doesn't work for me... Any idea why it's not working?

EDIT: Actually I'm really ashamed and stupid: The problem was I had multiple <select> lists in my page marked with class .closedStatus... Of course, it didn't work that way...

Thanks for your help anyway!

Upvotes: 0

Views: 7780

Answers (2)

softsdev
softsdev

Reputation: 1509

it will work for you

change

$('.closedStatus option[value=-1]').attr('selected','selected');

instead

$('.closedStatus').first().val('-1');

Upvotes: 1

colestrode
colestrode

Reputation: 10668

You can look for the option element whose value = -1 and then set the selected property to true:

$('select.closedStatus').find('option[value="-1"]').prop('selected', true); 

Working Demo

What you are doing ($('.closedStatus').first().val('-1');) won't work because that is selecting the first child of the select, which is an option, and setting the value of that option. I'm not sure this would have any effect (I don't think you can call val('-1') on an option element), but if it does work, it would change the value of the first option to -1 without affecting the select at all.

Upvotes: 4

Related Questions