JQuery select2 set default value from an option in list? - javascript

I want to be able to set the default/selected value of a select element using the JQuery Select2 plugin.

One more way - just add a selected = "selected" attribute to the select markup and call select2 on it. It must take your selected value. No need for extra JavaScript. Like this :
Markup
<select class="select2">
<option id="foo">Some Text</option>
<option id="bar" selected="selected">Other Text</option>
</select>
JavaScript
$('select').select2(); //oh yes just this!
See fiddle : http://jsfiddle.net/6hZFU/
Edit: (Thanks, Jay Haase!)
If this doesn't work, try setting the val property of select2 to null, to clear the value, like this:
$('select').select2("val", null); //a lil' bit more :)
After this, it is simple enough to set val to "Whatever You Want".

The above solutions did not work for me, but this code from Select2's own website did:
$('select').val('US'); // Select the option with a value of 'US'
$('select').trigger('change'); // Notify any JS components that the value changed
Webpage found here
Hope this helps for anyone who is struggling, like I was.

$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');

One way to accomplish this is...
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
So basically you first initalize the plugin then specify the default value using the 'val' parameter. The actual value is taken from the specified option, in this case #1. So the selected value from this example would be "bar".
<select class=".select2">
<option id="foo">Some Text</option>
<option id="bar">Other Text</option>
</select>
Hope this is useful to someone else.

For 4.x version
$('#select2Id').val(__INDEX__).trigger('change');
to select value with INDEX
$('#select2Id').val('').trigger('change');
to select nothing (show placeholder if it is)

Came from the future? Looking for the ajax source default value ?
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
You're welcome.
Reference:
https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2

Step 1: You need to append one blank option with a blank value in your select tag.
Step 2: Add data-placeholder attribute in select tag with a placeholder value
HTML
<select class="select2" data-placeholder='--Select--'>
<option value=''>--Select--</option>
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
</select>
jQuery
$('.select2').select2({
placeholder: $(this).data('placeholder')
});
OR
$('.select2').select2({
placeholder: 'Custom placeholder text'
});

e.g.
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
you can see it here https://select2.org/programmatic-control/add-select-clear-items

Don't know others issue, Only this code worked for me.
$('select').val('').select2();

Normally we usually use active but in select2, changes to selected="selected"
Example using Python/Flask
HTML:
<select id="role" name="role[]" multiple="multiple" class="js-example-basic-multiple form-control">
{% for x in list%}
<option selected="selected" value="{{x[0]}}">{{x[1]}}</option>
{% endfor %}
</select>
JQuery:
$(document).ready(function() {
$('.js-example-basic-multiple').select2();
});
$(".js-example-theme-multiple").select2({
theme: "classic",
placeholder: 'Select your option...'
});

It's easy. For example I want to select option with value 2 in default:
HTML:
<select class="select2" id="selectBox">
<option value="1">Some Text</option>
<option value="2">Other Text</option>
</select>
Javascript:
$("#selectBox").val('2').trigger('change')

$('select').select2("val",null);

If you are using an array data source you can do something like below -
$(".select").select2({
data: data_names
});
data_names.forEach(function(name) {
if (name.selected) {
$(".select").select2('val', name.id);
}
});
This assumes that out of your data set the one item which you want to set as default has an additional attribute called selected and we use that to set the value.

For ajax select2 multiple select dropdown i did like this;
//preset element values
//topics is an array of format [{"id":"","text":""}, .....]
$(id).val(topics);
setTimeout(function(){
ajaxTopicDropdown(id,
2,location.origin+"/api for gettings topics/",
"Pick a topic", true, 5);
},1);
// ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

Related

Remove and add values from dropdown using javascript/jQuery

I am trying to achieve the following thing in my code but it is getting complicated.
I have 'n' dropdowns with or without duplicate values in it.
for simplicity lets assume following scenario:
dropdown1:
<select>
<option>100</option>
<option>200</option>
<option>102</option>
</select>
dropdown 2:
<select>
<option>100</option>
<option>200</option>
<option>201</option>
</select>
dropdown3 :
<select>
<option>100</option>
<option>300</option>
<option>301</option>
</select>
case1:
if user select value 100 from dropdown 1 then 100 should be removed from all the dropdowns.and when user change dropdown 1 value from 100 to 200 then 100 should be added back to all the dropdowns and 200 should be removed from all the dropdowns.
removing seems easy but adding back values is little difficult.
how can I maintain a list or some other data structure to remember which value to add and where incase of multiple value change? is there any advance jquery feature or generic javacript logic i can use ?
If it is sufficient to just disable the option instead of actually removing it, the following could work for you. You might want to adapt the handling of the selects when initially loading the site.
$('select option[value="' + $('select').eq(0).val() + '"]').not(':eq(0)').prop('disabled', true);
$('select').on('change', function() {
var val = $(this).val();
$('select option').prop('disabled', false);
$('select option[value="' + val + '"]').not($(this)).prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='102'>102</option>
</select>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='201'>201</option>
</select>
<select>
<option value='100'>100</option>
<option value='300'>300</option>
<option value='301'>301</option>
</select>
It would be better to set display to none instead. Hence, you will avoid the complications of adding or removing in the appropriate order.
So, you can easily return them visible.
$( "option" ).each(function( index ) {
$(this).css("display", "");
});
$("#drop").change(function () {
var selected_value=$(this).val();
var dropdown=$(select);
for(i=0;i<dropdown.length;i++){
$("dropdown[i] option[value=selected_value]").remove();
}
});
Set id of first dropdown="drop"
Here select the value and define it S a variable loop through dropdown with in page remove option when value=selected_value

remove all options from select jquery but only one

I have a select that contain this values:
<select id="lstCities" class="valid" name="City">
<option value="OSNY">OSNY</option>
<option value="dd">dd</option>
<option value="OSffNY">OSffNY</option>
<option value="ANTONY">ANTONY</option>
<option value="0">Autre...</option>
</select>
How can I delete all options but i would like to keep only
<option value="0">Autre...</option>
My problem is my list is dynamic sometimes I have 3,5,7,.... select + the last one <option value="0">Autre...</option>
select all options, then exclude the one with that value :
$('#lstCities option[value!="0"]').remove();
FIDDLE
Try
$('#lstCities option:lt(-1)').remove()
Demo: Fiddle
$('#lstCities option[value!=0]').remove()
You should remove by value and not rely on the position of the option element to keep.
If the option is always the last one, I hope this JavaScript code can help you:
var lastNode = $("#lstCities option").last();
var option = { value:lastNode.val(), text:lastNode.text() };
$('#lstCities').find('option').remove().end().append($('<option>',{
value:option.value,
text:option.text,
}));
Learned from this post
This worked for me:
$("#selectList option").remove();

Alternative to .change in jquery?

I'm trying to fire an ajax event, and passing the value of select list options as arguments in the ajax call. Unfortunately, I'm firing the call on the .change event, and it is passing the values of the select option before the new option has been selected (i.e passing the previously selected options values). Is there an event which will get the current values of the option selected? Much thanks in advance,
<select id='theList'>
<option> Option 1</option>
<option> Option 2</option>
</select>
In the JS:
$('#theList').change( function() {
$.getJSON('Home/MethodName', { var1: Option1Value, var2: MiscValue}, function(data) {
//Execute instructions here
}
)});
I wanted to use .trigger, but I think that fires beforehand as well.
I think .change() is what you want, but you're misusing it. The change event fires after the value has changed. In your handler, you need to read the new value:
$('#theList').change( function() {
var value = $('#theList').val();
$.getJSON('Home/MethodName', { your_key: value }, function(data) {
// ...
}
)});
You also might want to set values on your <option> tags:
<option value="something"> Option 2</option>
You must be doing something wrong when getting the current select value. The following works correctly for me.
http://jsfiddle.net/TJ2eS/
<select id="demo">
<option value=""></option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
$("#demo").change(function() {
alert("current select value " + $(this).val());
});
A word of warning, .change is now defunct, you should use...
.on('change', function()
Like that.

Get selected option data using Jquery or javascript

I have to get the selected option data whose option value is known. I have the selected option value and I want the data which is wrapped between the option.
For example in the following select:
<select name="oi_report_contact[sex]" id="oi_report_contact_sex">
<option value="1">Male</option>
<option value="2">Female</option>
<option value="3">Other</option>
</select>
I have value 1, I need to get the data "Male" through Jquery or Javascript.
Please note : $('#oi_report_contact_sex').val(); will give 1 and not male, when 1 is selected.
You just have to call
var content = $('#oi_report_contact_sex option:selected').html();
to get the inner content of the selected option.
You can use .text() method to get the text value. Like this.
$('#oi_report_contact_sex').on('change', function () {
alert($('#oi_report_contact_sex').val());
alert($('#oi_report_contact_sex option:selected').text());
});
$("#oi_report_contact_sex").find('option:selected').text();
You can try:
$("#oi_report_contact_sex option[value='" + $("#oi_report_contact_sex").val() + "']").text()
jsFiddle link: http://jsfiddle.net/ARBb2/1/

How can i replace value from the option tag value attribute

I have a below scenario. Actually, by the process the after rendering the html dropdown box is display the value like below
<select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>
<option value="<span id="_SE_CP" _SE_CPt="default">Lakeside</span>">
Lakeside
</option>
<option value="<span id="_SE_CP" _SE_CPt="default"></span>">
Alvaston
</option>
by some process, it is using some span tag there, i need only url in the value attribute like below
<select id="ht" class="input-box quick-jump-menu" name="ht">
<option selected="selected" value="">Jump straight to a below option</option>
<option value="Google.co.uk">
Lakeside
</option>
<option value="http://www.google.com">
Alvaston
</option>
Here, i need only set the URL value in the "Value" attribute of the "option" tag. i think this can be done through jquery.
Please suggest any one if possible and help will be much appreciated
​var tempDiv=$('<div/>');
$('#ht option').each(function(){
tempDiv.html($(this).val());
$(this).val(​​​​​​​​​​​​​​​​​​​​​​​​​​​tempDiv.find('a').attr('href'));
});
The above code uses a temporary div (tempDiv) to capture the html from the option value and extract the href value.
Demo (select an option): http://jsfiddle.net/A7nyd/
[Update] this is actually the same answer as #chrisgonzalez.
If you're rendering the option tag like this and you want to change it on the client side, here's a quick but dirty solution:
$("#ht option").each(function(){
$(this).attr("value", $($(this).attr("value")).find("a").attr("href"));
});
First off there is an error with the current HTML.. All the html inside of the value have double quotes.
Encase that inside single Quotes or escape the ones inside.
Try this
​$('#ht')​.after('<div id="check"></div>');
​$('#ht option').each(function(){
if(this.value != ''){
var $check = $('#check');
var str = this.value;
$check.append(str);
var href = $check.find('a').attr('href');
this.value = href;
$check.empty();
}
});
$('#check').remove();
Check Fiddle
with jQuery:
$('option').attr({value: 'new src'});
Try this:
$("#ht option").each(function()
{
$(this).val($(this).val().find("a").attr("href"));
});

Categories

Resources