Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select2 get value of select tag?

Hello 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 code for getting selected value.

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

This is return a text like first,second,three and I want to get 1,2,3.
Means I need the value of select box, not text.

like image 764
Renish Khunt Avatar asked Nov 11 '13 14:11

Renish Khunt


People also ask

How to change option Select2 value in jQuery?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

How to append data in Select2 using jQuery?

var select2_existing_data = $('#select2_id'). select2('data'); select2_existing_data. append(new_data);

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.


2 Answers

$("#first").val(); // this will give you value of selected element. i.e. 1,2,3. 
like image 57
somesh Avatar answered Oct 01 '22 03:10

somesh


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

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

Can you please post your select2() function code

like image 41
Krish R Avatar answered Oct 01 '22 03:10

Krish R