Advertisement
Advertisement


How do I get the selected element by name and then get the selected value from a dropdown using jQuery?


Question

I am able to find my select element by name, but I'm having trouble finding the selected value associated with it.

Here is my code below:

<select  name="a[b]" onchange='mySelectHandler("a[b]")'>
     <option value='Choice 1'>Choice 1</option>
     <option value='Choice 2'>Choice 2</option>

</select>

then, in my handler I am using:

function mySelectHandler(name){
     var mySelect = $('select[name=' + name)
     // try to get selected value
     // alert ("selected " + mySelect.val())
     console.log("object "+ mySelect.toSource());
  }

The result of my print to the log is:

object ({length:0, prevObject:{0:({}), context:({}), length:1}, context:({}), selector:"select[name=a[b]"})

Any ideas as to how to do this?

2013/11/22
1
14
11/22/2013 8:39:31 PM

Accepted Answer

Your selector is a little off, it's missing the trailing ]

var mySelect = $('select[name=' + name + ']')

you may also need to put quotes around the name, like so:

var mySelect = $('select[name="' + name + '"]')
2012/08/10
31
8/10/2012 8:58:43 PM


Remove the onchange event from the HTML Markup and bind it in your document ready event

<select  name="a[b]" >
     <option value='Choice 1'>Choice 1</option>
     <option value='Choice 2'>Choice 2</option>
</select>​

and Script

$(function(){    
    $("select[name='a[b]']").change(function(){
       alert($(this).val());        
    }); 
});

Working sample : http://jsfiddle.net/gLaR8/3/

2012/08/10

instead of

mySelect.toSource()

use

mySelect.val()
2012/08/10

MrOBrian's answer shows why your current code doesn't work, with the missing trailing ] and quotes, but here's an easier way to make it work:

onchange='mySelectHandler(this)'

And then:

function mySelectHandler(el){
     var mySelect = $(el)
     // get selected value
     alert ("selected " + mySelect.val())
  }

Or better still, remove the inline event handler altogether and bind the event handler with jQuery:

$('select[name="a[b]"]').change(function() {
    var mySelect = $(this);
    alert("selected " mySelect.val());
});

That last would need to be in a document.ready handler or in a script block that appears after the select element. If you want to run the same function for other selects simply change the selector to something that applies to all, e.g., all selects would be $('select'), or all with a particular class would be $('select.someClass').

2012/08/10

Try this to get value from select element by Element Name

$("select[name=elementnamehere]").val();

To add to the answers here, ensure there's no space between the select and [name...

Wrong:

'select [name=' + name + ']'
       ^

Right:

'select[name=' + name + ']'
2016/11/22