最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - set select option value to null - Stack Overflow

programmeradmin5浏览0评论

I have to disable all the select menus in a div and also set their value to null.

I am using the following code to disable the select menus:

  var div_contents =document.getElementById("div1");
  var elements = div_contents.getElementsByTagName("select");
  for (i=0; i<elements.length; i++) {
      elements[i].disabled = true;
  }

However, I am not able to set the value of the select tag to null.

Also I don't have the null option inside the select tag:

<select id="test1" name="test1">
    <option value="a">aa</option>
    <option value="b">bb</option>
    <option value="c">cc</option>
</select>

How can I set the value of a select list to null, given that I don't have the null option?

I have to disable all the select menus in a div and also set their value to null.

I am using the following code to disable the select menus:

  var div_contents =document.getElementById("div1");
  var elements = div_contents.getElementsByTagName("select");
  for (i=0; i<elements.length; i++) {
      elements[i].disabled = true;
  }

However, I am not able to set the value of the select tag to null.

Also I don't have the null option inside the select tag:

<select id="test1" name="test1">
    <option value="a">aa</option>
    <option value="b">bb</option>
    <option value="c">cc</option>
</select>

How can I set the value of a select list to null, given that I don't have the null option?

Share Improve this question edited Dec 12, 2011 at 16:56 Wayne 60.4k15 gold badges135 silver badges128 bronze badges asked Dec 12, 2011 at 16:51 tanyatanya 2,9857 gold badges34 silver badges50 bronze badges 3
  • It's not clear to me what you mean. Do you want to remove all of the options completely? – Wayne Commented Dec 12, 2011 at 17:05
  • your code is right, you are just disabling the boxed to set the value null use elements[i].value = '' – Punit Commented Dec 12, 2011 at 17:08
  • Using 'elements[i].selectedIndex = -1;' seems to have done the trick – tanya Commented Dec 13, 2011 at 10:47
Add a comment  | 

3 Answers 3

Reset to default 14

If you want to show no selection, you should set its selectedIndex to -1.

elements[i].selectedIndex = -1;

You could try setting the element's value property:

elements[i].value = '';

This one is working. I have tested it.

elements[i].value = ' ';

elements[i].trigger('change'); 
发布评论

评论列表(0)

  1. 暂无评论