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

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

I have the following HTML

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

    Why not add a variable for the element's Id and make it a reusable function?

    function SelectElement(selectElementId, valueToSelect)
    {    
        var element = document.getElementById(selectElementId);
        element.value = valueToSelect;
    }
    
    0 讨论(0)
  • 2020-11-22 06:51

    You can use this function:

    selectElement('leaveCode', '11')
    
    function selectElement(id, valueToSelect) {    
        let element = document.getElementById(id);
        element.value = valueToSelect;
    }
    
    0 讨论(0)
  • 2020-11-22 06:51
    
    function foo(value)
    {
        var e = document.getElementById('leaveCode');
        if(e) e.value = value;
    }
    
    
    0 讨论(0)
  • 2020-11-22 06:53

    If using PHP you could try something like this:

    $value = '11';
    $first = '';
    $second = '';
    $third = '';
    $fourth = '';
    
    switch($value) {
                case '10' :
                    $first = 'selected';
                break;
                case '11' :
                    $second = 'selected';
                break;
                case '14' :
                    $third = 'selected';
                break;
                case '17' :
                    $fourth = 'selected';
                break;
            }
    
    echo'
    <select id="leaveCode" name="leaveCode">
      <option value="10" '. $first .'>Annual Leave</option>
      <option value="11" '. $second .'>Medical Leave</option>
      <option value="14" '. $third .'>Long Service</option>
      <option value="17" '. $fourth .'>Leave Without Pay</option>
    </select>';
    
    0 讨论(0)
  • 2020-11-22 06:54

    Suppose your form is named form1:

    function selectValue(val)
    {
      var lc = document.form1.leaveCode;
      for (i=0; i&lt;lc.length; i++)
      {
        if (lc.options[i].value == val)
        {
            lc.selectedIndex = i;
            return;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 06:54

    Should be something along these lines:

    function setValue(inVal){
    var dl = document.getElementById('leaveCode');
    var el =0;
    for (var i=0; i<dl.options.length; i++){
      if (dl.options[i].value == inVal){
        el=i;
        break;
      }
    }
    dl.selectedIndex = el;
    }
    
    0 讨论(0)
提交回复
热议问题