Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting an option on dropdown <select> programmatically

I have a page on a website that I am updating automatically from a web service. I am trying to set the value of a dropdown <select> before the page is loaded and I can see when I select the drop down the value I wanted is already highlighted however I want that option to be selected not highlight. This is my code in javascript:

document.getElementById('walkForAmount').selectedIndex = object.get("WalkForTime");

which is called automatically when the page is loaded. It sets the selectedIndex to an int 0 -15. And the HTML code:

  <select id = "walkForAmount" name="walkForAmount" style="margin-left:2em;margin-top:-1em; width:4em;">
                                <option>-</option>
  </select>

Edit: below id the JS I use to generate options

$(document).ready(function() { 

    $("#walkForAmount").select2({

    }); 

    $("#walkForType").select2({

    });

    for (i = 1; i < 16; i++) {

    $("#walkForAmount").append("<option>"+i+"</option>");

    }

});
like image 923
Bradley Armstrong Avatar asked Jun 11 '26 00:06

Bradley Armstrong


1 Answers

If you're using Select2, you can update your selection via

$("#walkForAmount").select2("val", "5"); // select "5"

Example: http://jsfiddle.net/verashn/aWvQr/1/

like image 91
VLS Avatar answered Jun 12 '26 16:06

VLS



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!