<\/script>')

JQuery add "selected" in the dropdown menu

I have a simple drop down menu with some options for example:

<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 the API to create the form, so I would prefer if there was a way through jquery to choose which of the parameters should be selected by default, depending on the parameter value.

Is it possible? Thanks for the help!

+3
source share
3 answers

Set the selected item programmatically:

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

This will allow you to select a country / people (0 account).

+13
source

Since you are using the API and you may not have control over the markup, you can add the string "[Default]" to the name of the entry 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());
+2

dd

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

Source: https://habr.com/ru/post/1784776/


All Articles