Jump to content

How do I get the text of a select element?


DeX

Recommended Posts

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.

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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.