Search code examples
javascriptdom-events

How to manipulate select option dynamically


I want to add option to select dynamically through JavaScript by clicking on a button. I want to make sure if it has an option already present then it add at n+1 option place only.

<select name="select">
 <option value="value1">Value 1</option> 
 <option value="value2" selected>Value 2</option>
 <option value="value3">Value 3</option>
</select>
<button onclick =addvalue()>clickme</button>enter code here
function addvalue()
 {
  var e=document.getElementById('select');
  var i =0;
  var abc = true;
  while(abc)
  {
   if (e.options[i].innerText==null)
   {
    abc =false;
   }
   i++;
 }
 alert(i);
}

But this is throwing an error that e.options[i].innerText is null or not an object. I will replace alert with code for adding option later.


Solution

  • e.options[i].innerText is null or not an object

    because there's no options[i] when i >= options.length. Check if it exists:

    function addvalue()
     {
      var e=document.getElementById('select');
      var i =0;
      var abc = true;
      while(abc)
      {
       if (!e.options[i] || e.options[i].innerText==null)
       {
        abc =false;
       }
       i++;
      }
      alert(i);
    }
    

    http://jsfiddle.net/eMQzC/

    It will alert 4, which I'm not sure is what you want to get. i is incremented once after abc was set to false.

    I think you may not need that while loop at all.

    function addvalue()
     {
      var e=document.getElementById('select'), i = e.options.length;
      alert(i);
    }
    

    This will alert 3, as it is the number of options in your select.