How do I programmatically set the value of a select box element using JavaScript?

后端 未结 17 1667
轮回少年
轮回少年 2020-11-22 06:33

I have the following HTML

相关标签:
17条回答
  • 2020-11-22 06:55

    Not answering the question, but you can also select by index, where i is the index of the item you wish to select:

    var formObj = document.getElementById('myForm');
    formObj.leaveCode[i].selected = true;
    

    You can also loop through the items to select by display value with a loop:

    for (var i = 0, len < formObj.leaveCode.length; i < len; i++) 
        if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
    
    0 讨论(0)
  • 2020-11-22 06:55
    document.getElementById('leaveCode').value = '10';
    

    That should set the selection to "Annual Leave"

    0 讨论(0)
  • 2020-11-22 06:55

    The easiest way if you need to:
    1) Click a button which defines select option
    2) Go to another page, where select option is
    3) Have that option value selected on another page

    1) your button links (say, on home page)

    <a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
    <a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
    

    (where contact.php is your page with select options. Note the page url has ?option=1 or 2)

    2) put this code on your second page (my case contact.php)

    <?
    if (isset($_GET['option']) && $_GET['option'] != "") {
    $pg = $_GET['option'];              
    } ?>
    

    3) make the option value selected, depending on the button clicked

    <select>
    <option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
    <option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
    </select>
    

    .. and so on.
    So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.

    0 讨论(0)
  • 2020-11-22 06:57

    Most of the code mentioned here didn't worked for me!

    At last, this worked

    window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options

        window.addEventListener("load", function () {
                // Selecting Element with ID - leaveCode  //
                var formObj = document.getElementById('leaveCode');
    
                // Setting option as selected
                let len;
                for (let i = 0, len = formObj.length; i < len; i++){
                    if (formObj[i].value == '<value to show in Select>') 
                     formObj.options[i].selected = true;
                }
        });
    

    Hope, this helps!

    0 讨论(0)
  • 2020-11-22 07:00
    function setSelectValue (id, val) {
        document.getElementById(id).value = val;
    }
    setSelectValue('leaveCode', 14);
    
    0 讨论(0)
提交回复
热议问题