Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

select

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?

like image 924
dt1000 Avatar asked Aug 10 '12 20:08

dt1000


People also ask

How do I get the selected value and current selected text of a dropdown box using jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How do I get a dropdown list and selected value?

One approach is to use the DropDownList SelectedItem Property to get the selectedItem( ListItem ), then use the ListItem. Value Property to get the corresponding value for the ListItem . lblResult. Text = DropdownList1.

How do you get the selected value of an element?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list.


2 Answers

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 + '"]')
like image 105
MrOBrian Avatar answered Oct 12 '22 13:10

MrOBrian


Try this:

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

This will get the selected value of your menu.

like image 25
Gromer Avatar answered Oct 12 '22 13:10

Gromer