Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select from option menu in javascript

I need to be able to change certain option from select menu to be as default (start) value when I do something.

For example when I declare it, English language is default value.

How to change that with the code and not with the click.

<form id="form1" name="form1" method="post" action="">
<select name="websites1" id="websites1" style="width:120px" tabindex="1">
    <option value="english" selected="selected"  title="images/us.gif">English</option>
    <option value="espanol" title="images/es.gif">Espanol</option>
    <option value="italian" title="images/it.gif">Italiano</option>
</select>
</form>

In the body tag I have declared:

<script type="text/javascript">
$(document).ready(function() {
$("body select").msDropDown();
});
</script>

I am using this SCRIPT

I have tried all of the bellow examples and none this is good for me.

What else can I do change default select value.

like image 767
user123_456 Avatar asked Feb 12 '26 05:02

user123_456


1 Answers

This is working for me as mentioned in the docs:

$('#websites1').msDropDown().data('dd').set('selectedIndex',2);

This will select italian ;)

/edit:

Keep in mind that @Patrick M has a more advanced approach and he posted his approach before I posted mine ;)

If you are having weird css issues like I did, try this undocumented stuff:

$('#websites1_msa_2').click(); // this will also select the italian

As you can see the id is generated by $('#websites1_msa_2') the id of the selectbox plus the $('#websites1_msa_2') index of the option item.

A bit hacky but works ;)

So you could then define a JavaScript-Function like this:

var jQueryImageDD_selectByName = function(name) {
  var children = $('#websites2_child').children();
  for(var i=0;i<children.length;i++) {
    var label = children[i].getElementsByTagName('span')[0].innerHTML;
    if(label === name) {
      children[i].click()
    }
  }
};

And then use it like this:

jQueryImageDD_selectByName('Italiano'); // will select Italiano :)
like image 115
Walialu Avatar answered Feb 14 '26 17:02

Walialu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!