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
  • 34,719
  • 24
  • 185
  • 251
Michelle Dupuis
  • 327
  • 1
  • 5
  • 19
  • 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,693
  • 2
  • 19
  • 19
  • `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
  • 206,216
  • 101
  • 402
  • 492
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
  • 1,975
  • 22
  • 27
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,255
  • 1
  • 33
  • 53
Andrew Thomson
  • 4,292
  • 3
  • 16
  • 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,255
  • 1
  • 33
  • 53
michael
  • 147
  • 2
  • 19