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

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?

This question is related to jquery select

The answer is


or you can simply do

$('select[name=a[b]] option:selected').val()

instead of

mySelect.toSource()

use

mySelect.val()

Try this:

$('select[name="' + name + '"] option:selected').val();

This will get the selected value of your menu.


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

Wrong:

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

Right:

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

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').


Try this to get value from select element by Element Name

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

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/