DeX Posted July 24, 2015 Share Posted July 24, 2015 I've seen many solutions on various searches using :selected or options:selected or .text(). I've tried all of these in both JavaScript and JQuery, all of them give me the same result. When I change the selected option of a SELECT element and then run the JavaScript statement, it returns the original SELECT value before I changed it, not the current value. I've tried both .text() and .val(), both give me the same result. I realize I'm not posting the code but it's literally just a SELECT element with 20 options and some JavaScript to get the text from that element. Quote Link to comment https://forums.phpfreaks.com/topic/297452-how-do-i-get-the-text-of-a-select-element/ Share on other sites More sharing options...
requinix Posted July 24, 2015 Share Posted July 24, 2015 What's your code. Quote Link to comment https://forums.phpfreaks.com/topic/297452-how-do-i-get-the-text-of-a-select-element/#findComment-1517252 Share on other sites More sharing options...
DeX Posted July 24, 2015 Author Share Posted July 24, 2015 That's odd, I wrote some quick sample code to post here for you but my example code works. I'll have to go back and work through my code to see where the problem is with that then. Oh well, I'll leave the example code here for someone else in case they're looking for one. <html> <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type ="text/javascript" > function test(element) { alert($(element).find(":selected").text()); } </script> </head> <body> <select onchange ="test(this);" > <option value ="1" >One</option> <option value ="2" >Two</option> </select> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/297452-how-do-i-get-the-text-of-a-select-element/#findComment-1517261 Share on other sites More sharing options...
requinix Posted July 24, 2015 Share Posted July 24, 2015 :selected + .text() is the simplest answer... Quote Link to comment https://forums.phpfreaks.com/topic/297452-how-do-i-get-the-text-of-a-select-element/#findComment-1517262 Share on other sites More sharing options...
scootstah Posted July 24, 2015 Share Posted July 24, 2015 Since you're not really using jQuery properly to start with, why not just stick with vanilla JS? function test(element) { alert(element.options[element.selectedIndex].innerHTML); } Quote Link to comment https://forums.phpfreaks.com/topic/297452-how-do-i-get-the-text-of-a-select-element/#findComment-1517281 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.