0

I want to read the value of the select tag which has [] in its id.

<select id="jobtype[]" class="dropDown" size="4" multiple="multiple" name="jobtype[]">
<option value="28">Activity staff/ Resort Rep</option>
<option value="1">Admin/ Secretarial/ Clerical</option>
<option value="2">Advertising/ Marketing/ PR</option>
<option value="29">Art/ Design</option>
<option value="30">Au Pair/ Nanny</option>

I am using the function below for setting 'selected':

$("#jobtype\\[\\] option").each(function()
            {
                //if ($(this).val() == 39)
                { 
                    $(this).attr('selected', 'selected');
                }

            });
}
Expedito
  • 7,493
  • 5
  • 27
  • 40
Manojkumar
  • 1,301
  • 4
  • 32
  • 49
  • 1
    Id attribute should not have [] – A. Wolff May 03 '13 at 17:06
  • 1
    Your code works as-is (if you fix the syntax errors around the brackets), but there are no options with a value of 39. http://jsfiddle.net/w7vRv/ – Kevin B May 03 '13 at 17:13
  • Take a look at this for why it shouldn't have square brackets: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Jason May 03 '13 at 17:14
  • yes there are no options with value = 39.. i just gave an example dude... – Manojkumar May 03 '13 at 17:16
  • As of HTML5, the only requirement for ID's is it must contain at least one character, and it can't contain any spaces. It doesn't say thing about not using `[]` – Kevin B May 03 '13 at 17:17
  • @ManojKumar In that case your code works as-is, if you fix the mis-matched brackets. – Kevin B May 03 '13 at 17:17
  • @adeneo following w3c html specs, but like Kevin said html5 is more permisive. But i'm sure you know that :) – A. Wolff May 03 '13 at 17:17
  • @roasted - In this day and age, hopefully everyone is using the HTML5 doctype, where it's completely valid with brackets in the ID selector. Should you use it just for fun, probably not, but some frameworks seems to do it all the same. – adeneo May 03 '13 at 17:21

3 Answers3

1

Yes, escaping the brackets should work just fine :

$("#jobtype\\[\\] option[value=39]").prop('selected', true);

FIDDLE

adeneo
  • 293,187
  • 26
  • 361
  • 361
0

It should work like this: http://jsfiddle.net/2e3tY/1/, so there are other problems:

Try:

  1. The select tag should be closed
  2. The jquery function should be wrapped in $(function() { } ); so it is called on doc ready.
Tallmaris
  • 7,485
  • 3
  • 25
  • 57
0

Your code seems to work just fine, here is the fiddle. http://jsfiddle.net/LxKrS/1/

$("#jobtype\\[\\] option").each(function() {
    if ($(this).val() == 29) { 
        $(this).attr('selected', 'selected');
    }    
});
Jose Vega
  • 9,800
  • 7
  • 37
  • 56