3

I have a simple dropdown menu with some options eg:

<select name='music_style' id='palmsForm-music_style'>
   <option value='1'  >Alternative and Indie</option>
   <option value='2'  >Clubs and Dance</option>
   <option value='3'  >Country/Folk</option>
   <option value='4'  >Hard Rock/Metal</option>
   <option value='5'  >Jazz/Blues</option>
   <option value='6'  >R&B/Urban Soul</option>
   <option value='7'  >Rap and Hip-Hop</option>
   <option value='8'  >Rock/Pop</option>
   <option value='9'  >Other</option>
</select>

I use a API for creating the form, so would prefer if there was a way to via jquery choose which of the options should be selected by default based upon the value of the option.

Is this possible? Thanks for helping!

Jacob
  • 3,521
  • 6
  • 26
  • 34

3 Answers3

13

Programmatically set the selected item:

$("#palmsForm-music_style").val(2);

This will select Country/Folk (0 count).

JasCav
  • 34,458
  • 20
  • 113
  • 170
2

You can also use this for selecting option from dd list

$(document).ready(function(){
var value= "6";
$('#palmsForm-music_style [value='+value+']').prop('selected', true);
});
Rehan Mobin
  • 558
  • 2
  • 14
2

Because you are using an API and you may not have control over the markup, you could add to the name of the default record something line " [Default]" and then use jQuery to select it.

Markup:

<select name='music_style' id='palmsForm-music_style'>
   ...
   <option value='5'>Jazz/Blues [Default]</option>
   ...
</select>

jQuery:

$("#palmsForm-music_style").val($("#palmsForm-music_style option:contains('[Default]')").val());
Tim Santeford
  • 27,385
  • 16
  • 74
  • 101