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 valu开发者_运维问答e='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!
Programmatically set the selected item:
$("#palmsForm-music_style").val(2);
This will select Country/Folk (0 count).
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());
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);
});
精彩评论