Jump to content

HTML -> Javascript


Rominall

Recommended Posts

I have this code in my HTML page.<script> function init(){ document.getElementById('OTWOpt1').onchange=function() { if(this.value==2) {this.options[this.selectedIndex].text='Right'; } if(this.value==1) {this.options[this.selectedIndex].text='Wrong'; } } } window.addEventListener? window.addEventListener('load',init,false): window.attachEvent('onload',init); </script> I want to move it to it's own JS page but I'm having all kinds of problems getting it to work. I know how to do the onchange for the select object but the syntax doesn't seem to be working. I tried going this way:function Submit1() { var x = document.getElementById("OTWOpt1"); var y = OTWOpt1.options[x.selectedIndex].value; alert(y) If y == 1 OTWOpt1.options[OTWOpt1.selectedIndex].text = "Wrong" elseIf y == 2 OTWOpt1.options[OTWOpt1.selectedIndex].text = "Right"} But no dice.

Edited by Rominall
Link to comment
Share on other sites

You set x to the element with id "OTWOpt1" here:var x = document.getElementById("OTWOpt1"); but then try to access it as OTWOpt1 here:var y = OTWOpt1.options[x.selectedIndex].value; The variable OTWOpt1 does not exist. Your browser's error console would have told you this if you had checked it.You should be using x:var y = x.options[x.selectedIndex].value; There are a few other places where you use OTWOpt1 instead of x as well.

Link to comment
Share on other sites

thanks. but when I changed it, it still didn't work. function Submit1() { var x = document.getElementById("OTWOpt1"); var y = x.options[x.selectedIndex].value; alert(y)If y == 1 x.options[x.selectedIndex].text = "Wrong"elseIf y == 2 x.options[x.selectedIndex].text = "Right"} If I comment out the if else the alert works fine and returns the expected value. So it's something in the if/else statements. If I replace the if/else with this x.options[x.selectedIndex].text = "Yes" that works. So what is wrong with the if/else statement? I tried else and elseIf. ????? I'm soooo confused.

Edited by Rominall
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...