0

I have problem with select tag. I google it and didn't find any solution regarding my question. here is one of the link... (Uncaught TypeError: Cannot read property 'value' of undefined)..... I have function on onchange event in the select tag some how like this..

 <select id="selectBox" onchange="_change();"> <?php $i = 1; while ($lastpage >= $i):?> <option><?php echo $i; ?></option> <?php $i++; endwhile; ?> </select> 

Possible jQuery code ...

 <script type="text/javascript"> function _change(evt) { alert(this.options[this.selectedIndex].value); }; </script> 

The question is Why I am getting undefined of undefined instead getting a value or property undefined so that I can go ahead and solve that prob... Thanks any help would more be appreciated...

2
  • The first step would be to remove the superfluous </a> from your server-side code. Commented Nov 10, 2014 at 13:12
  • sorry it isn't present in the code but mistakenly added here Commented Nov 10, 2014 at 16:40

2 Answers 2

1

You have to pass the referrer element this to your javascript function.

Code:

<select id="selectBox" onchange="_change(this);"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> 

js:

function _change(el) { alert(el.options[el.selectedIndex].value); }; 

Demo: http://jsfiddle.net/g5hzph1y/

Sign up to request clarification or add additional context in comments.

Comments

0
***SIMPLEST REPRESENTATION:-*** <!DOCTYPE html> <html> <body> Select a fruit and click the button: <select id="mySelect"> <option value="11">Apple</option> <option value="12">Orange</option> <option value="13">Pineapple</option> <option value="14">Banana</option> </select> <button type="button" onclick="myFunction()">Display index</button> <script> function myFunction() { var x = document.getElementById("mySelect").selectedIndex; var y = document.getElementById("mySelect").options; alert("Index: " + y[x].index + " text is " + y[x].text + " and value is " + y[x].value); } </script> </body> </html> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.