2

I have the following HTML which defines my selector:

<select name="zoom_cat[]" style="margin-left:15px;"> <option value="-1" selected="selected">All</option> <option value="0">News</option> <option value="1">Publications</option> <option value="2">Services</option> <option value="3">Industries</option> </select> 

And I am trying to set the selected option to All (value -1). For some reason this jquery code is having no effect (same option remains selected):

$('input[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected'); 
2
  • 1
    see stackoverflow.com/questions/1280499/jquery-set-select-index duplicate Commented Apr 16, 2012 at 21:53
  • You're trying to set the select element (despite using input in the selector) to the value of the option that's already selected, and you're surprised that it doesn't change anything? Commented Apr 16, 2012 at 21:53

5 Answers 5

4
$('select[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected'); 

instead of input

Sign up to request clarification or add additional context in comments.

2 Comments

selected is a property (prop()), not an attribute. JS Fiddle.
@DavidThomas, prop and attr both work, if you use them right. It's not wrong to use attr here. Changing the selected attribute also changes the property automatically and vise versa. .attr('selected'): selected .prop('selected'): true
0

Use select instead of input

$('select[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected'); 

working sample : http://jsfiddle.net/Est9D/4/

You can do it in more simple way

 $('select[name="zoom_cat[]"]').val("-1") 

Sample : http://jsfiddle.net/Est9D/7/

Comments

0

As Matt above said, you should use select in your selector, not input, they are different elements. Also setting the selected attribute will not work on <=IE7, so ideally you should do $('select[name="zoom_cat[]"]').val('-1');

Comments

0

You can do this: (not attr as suggested by someone but prop)

$('select[name="zoom_cat[]"] option[value="-1"]').prop('selected', 'selected'); 

Comments

0

You need to escape special characters in your selector.

See: http://api.jquery.com/category/selectors/

So try this instead:

$('input[name="zoom_cat\\\\[\\\\]"] option[value="-1"]').attr('selected', 'selected'); 

1 Comment

You must escape square brackets in a jquery selector for it to work correctly in IE7.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.