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');
Cœur
  • 37,241
  • 25
  • 195
  • 267
Michelle Dupuis
  • 337
  • 1
  • 5
  • 20
  • 1
    see http://stackoverflow.com/questions/1280499/jquery-set-select-index/ duplicate – Collin Price Apr 16 '12 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? – David Thomas Apr 16 '12 at 21:53

5 Answers5

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

instead of input

Matt Mombrea
  • 6,793
  • 2
  • 20
  • 20
  • `selected` is a property (`prop()`), not an attribute. [JS Fiddle](http://jsfiddle.net/davidThomas/L7BkN/). – David Thomas Apr 16 '12 at 21:55
  • @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` – Geekfish Apr 16 '12 at 22:03
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/

Shyju
  • 214,206
  • 104
  • 411
  • 497
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');

Geekfish
  • 2,173
  • 23
  • 28
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');
David
  • 3,285
  • 1
  • 37
  • 54
Andrew Thomson
  • 4,572
  • 3
  • 18
  • 15
0

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

$('select[name="zoom_cat[]"] option[value="-1"]').prop('selected', 'selected');
David
  • 3,285
  • 1
  • 37
  • 54
michael
  • 146
  • 3
  • 19