dt1000 dt1000 - 1 year ago 79
jQuery Question

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>


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?

Answer Source

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 + '"]')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download