April 22, 2012

innerHTML wont change if a changebox changes

Question by John Smith

I have a basic list:

<select id = "opt">
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

Now I must change the selected items in JS. Its done, and then I need the content of this select items (.innerHTML).
But sadly, the innerHTML say nothing is selected… how to fix this?

EDIT: here is the code:

for (var count = 0; count < document.getElementById('opt').childNodes[0].options.length; count++)
{
 if (document.getElementById('opt').childNodes[0].options[count].value == 7) { document.getElementById('opt').childNodes[0].options[count].selected = true; break; }
}
var obj = document.getElementById('opt');
alert (obj.innerHTML);

and that alert() just displays the original HTML code

Answer by Starx

You can do this as such

var opt = document.getElementById("opt");
var listLength = opt.options.length;
for(var i =0; i< listLength; i++) {
   if(opt.options[i].selected) {
      opt.options[i].textContent = 'the change HTML';
   }
}

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!