user1269625
user1269625

Reputation: 3209

jQuery unselect dropdown menu

I have a dropdown menu for states. The first option is 'Please select state' and its value is 0 but a state is always selected it as the user picks a state from a previous page and it somehow gets state and selects it. I want it to be at value 0.

I have this code....

$('#shipstate option').attr('selected', '');

but this sets all my options to selected.

What Am I doing wrong?

Upvotes: 2

Views: 20619

Answers (4)

Athul Nalupurakkal
Athul Nalupurakkal

Reputation: 440

You can select the option using the following method.

 $('#shipstate option[value="0"]').prop('selected', true);

This is the best method to deselect the option.

 $('#shipstate option[value="0"]').prop('selected', false);

Upvotes: 0

Derek
Derek

Reputation: 2735

You would set the value to the select element directly by using .val() jquery api.

Method:.val()

Get the current value of the first element in the set of matched elements or set the value of every matched element.

Ref : http://api.jquery.com/val/

$('#shipstate').val(0);

Upvotes: 1

cernunnos
cernunnos

Reputation: 2806

You want to set the value of an element that happens to be a select to 0, now turn this phrase into jquery:

$('#shipstate').val(0) 

Upvotes: 6

thecodeparadox
thecodeparadox

Reputation: 87073

Try this:

$('#shipstate').val('');

OR

$('#shipstate').val(0);

And this will select the default ie. first option.

You can also do:

$('#shipstate').attr('selectedIndex', 0);

Upvotes: 2

Related Questions