How to select a value in dropdown javascript?

后端 未结 10 687
星月不相逢
星月不相逢 2020-11-27 03:17

i have a drop down like this


                        
    
提交评论

  • 2020-11-27 03:47

    Using some ES6:

    Get the options first, filter the value based on the option and set the selected attribute to true.

    window.onload = () => {
    
      Array.from(document.querySelector(`#Mobility`).options)
        .filter(x => x.value === "12")[0]
        .setAttribute('selected', true);
    
    };
    <select style="width: 280px" id="Mobility" name="Mobility">
      <option selected disabled>Please Select</option>
      <option>K</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
      <option>7</option>
      <option>8</option>
      <option>9</option>
      <option>10</option>
      <option>11</option>
      <option>12</option>
    </select>

    0 讨论(0)
  • 2020-11-27 03:48

    This may do it

    document.forms['someform'].elements['someelement'].value

    0 讨论(0)
  • 2020-11-27 03:50

    Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

    http://www.w3schools.com/jsref/dom_obj_select.asp

    Update

    This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

    0 讨论(0)
  • 提交回复
    热议问题