JQuery select2 get select tag value?

Hi friends, this is my code:

<select id='first'> <option value='1'> First </option> <option value='2'> Second </option> <option value='3'> Three </option> </select> 

This is my select2 code:

 $("#first").select2(); 

Below is the code to get the selected value.

 $("#first").select2('val'); // It returns first,second,three. 

This returns text like first,second,three , and I want to get 1,2,3 .
So I need a select value, not text.

+50
jquery jquery-select2
Nov 11 '13 at 14:03
source share
8 answers
 $("#first").val(); // this will give you value of selected element. ie 1,2,3. 
+75
Nov 11 '13 at 14:17
source share

To get a Select element, you can use $('#first').val();

To get the text of the selected value - $('#first :selected').text();

Could you post your select2() function code

+36
Nov 11 '13 at 14:07
source share

$("#first").select2('data') will return all data as a map

+22
Jan 11 '16 at 7:53 on
source share

This solution allows you to forget the select element. Useful if you do not have an identifier on the selected items.

 $("#first").select2() .on("select2:select", function (e) { var selected_element = $(e.currentTarget); var select_val = selected_element.val(); }); 
+6
Sep 02 '16 at 16:07 on
source share

If you are using ajax , you may need to get an updated value for the selection on the right after the selection.

 //Part 1 $(".element").select2(/*Your code*/) //Part 2 - continued $(".element").on("select2:select", function (e) { var select_val = $(e.currentTarget).val(); console.log(select_val) }); 

Credits: Stephen Johnston

+4
Sep 05 '16 at 20:20
source share

See this script .
Basically, you want to get the value your option -tags, but you are always trying to get the value of your select - node with $("#first").val() .

So, we have to select the option tags, and we will use the jQuerys selector:

 $("#first option").each(function() { console.log($(this).val()); }); 

$("#first option") selects each option , which is a child of the element with id first .

+2
Nov 11 '13 at 14:16
source share

Try the following:

 $('#input_id :selected').val(); //for getting value from selected option $('#input_id :selected').text(); //for getting text from selected option 
+2
Sep 04 '17 at 8:52
source share

Simple answer:

 $('#first').select2().val() 

and you can also write:

  $('#first').val() 
0
Nov 23 '17 at 9:18
source share



All Articles