I have a Select2 working fine attached to a select list but when someone enters a new item and I rebind the select list and try to programmatically select the new item, it refuses to display.
There are a number of other posts re this but their solutions don't work for me.
Use .select2("val", value). Does nothing.
Use .select2("data", value). Does nothing. Not sure how this is supposed to be different.
Use the InitSelection option to set a value. This leads to the following error message: Uncaught Error: Option 'initSelection' is not allowed for Select2 when attached to a select element.
In the Ajax success function after adding the new option to the database, I have the following Javascript:
BindDishes(RestaurantID); //rebinds the select list successfully
$('#hidDishID').val = data.DishID; //populates a hidden field
var arr = '[{id: "' + data.DishID + '", text: "' + data.DishName + '"}]';
$("#dd").select2("data", arr);
So in this latest iteration I have tried to supply an array with the id and text from the select list item as per another suggested solution but still nothing occurs. What am I doing wrong? Is this impossible when using Select2 with a select list?
Edit: I have the following line in MVC that creates the Select list:
#Html.DropDownGroupListFor(m => m.DishID, Model.GroupedSelectList, "Select a dish", new { id="dd",style="width:470px;" })
which must be causing the problem by binding to DishID from the model which was originally blank when it came from the server. DropDownGroupListFor is just an HTML helper that allows for using OptionGroups in a Select but it must be the binding that is a problem. What is the best approach here, to bind in a different way or to somehow update the model's DishID, not sure of the best practice?
var $example = $(".js-example-programmatic").select2();
$example.val("CA").trigger("change");
You need to destroy your select2 before adding/modifying items. If you do, then your select2 will respond just like its bound first time
Select2 Dropdown Dynamically Add, Remove and Refresh Items from
Related
I'm using a combination of JQuery EasyUI and Select2 to be able to drag options from a right panel, onto a left select box.
In the original HTML, the select boxes are empty, and I only "add" anything to them if I drop an option on them,
<form id="section1">
<select class="select2" class="drop_target" id="selected_options" name="selected_options"></select>
<div>
<div class="draggable_option" data-id="1234">1234</div>
</div>
</form>
<form id="section2">
<select class="select2" class="drop_target"></select>
<div>
<div class="draggable_option" data-id="1235" id="selected_options" name="selected_options">1235</div>
</div>
</form>
Then in javascript, I do something like this,
$('.drop_target').droppable({
accept: '.draggable_option',
onDrop:function(e, source){
var $dragged_source = $(source);
var $drop_target = $(this);
}
});
The problem comes at this point, if you're dynamically adding things to the select, you have to check it doesn't exist, and if it doesn't, you create a new option, and add it,
var new_option = {
id: $drag_source.data('id'), data_id: $drag_source.data('id'),
text: $drag_source.val(), selected: true};
// Set the value, creating a new option if necessary
if (!$drop_target.find("option[value='" + new_option.id + "']").length) {
// Append it to the select
$drop_target.append(new Option(
new_option.text, new_option.id, true, true)).trigger('change');
}
var data = $drop_target.select2('data');
$drop_target.select2('data', data.concat([new_option]));
Clear as mud? Unfortunately it goes wrong at this point. While all calls to .select2 from $drop_target work as expected, this is not the select that was originally in the HTML, this is a div that select2 created, after hiding the original select, with an id attribute like id="s2id_selected_options". So when we append the new option to it, it doesn't get added to the select, and gets added to select2's div incorrectly instead.
My HTML pseudocode is deliberately set up in this "obtuse" way, because my page is like that. I have multiple forms, and multiple "identical" selects in those forms, generated by WTForms. So the "general" method of selecting your select by id, $('#selected_options') doesn't work correctly.
What I need to do, within the javascript, is gain access directly to the original, now hidden, select, and I can't access it via id.
When you have access to one of the elements that's "associated" with the generated by select2, you can access meta information for it via .data('select2'), or in this instance,
$(this).data('select2');
In here, there's loads of metadata that select2 uses (which you can see if you browse the source). For this question, to get the original select or input element, you can use,
var $drop_target = $(this).data('select2').opts.element;
Whether you're using a select, or an input, this gives you a jQuery element linking to it. If you're using a select, and are only interested in that, you can use the shorter option,
var $drop_target = $(this).data('select2').select;
This may be in the docs somewhere, but I was unable to find it, and I'm also not able to find it by searching now, because searching the docs for "data" and "select2" returns a result for nearly every page of their docs (hence the reason I'm answering this question myself, to hopefully save others the trouble).
I'm using Select2 in a combination of dropdown menus. I have one menu for "Countries" and one for "States/Provinces". Depending on the country that is chosen, the "States/Provinces" dropdown changes in content. The states/provinces are pulled with ajax from a database and then displayed this way:
$display_output = '<select style="width:350px;" tabindex="2" name="state" id="state" data-placeholder="Choose a Country..."> ';
$display_output .= '<option value="" selected>Select a State</option> ';
while ($state_details = $this->fetch_array($sql_select_states))
{
$display_output .= '<option value="' . $state_details['id'] . '" ' . (($selected_value == $state_details['id']) ? 'selected' : ''). '>' . $state_details['s.name'] . '</option>';
}
$display_output .= '</select>';
So far, so good. All the provinces change correctly, however when it initially loads, the Select2 shows "undefined" for the states dropdown, even though I have it set as
data-placeholder="Choose a Country..."
I'm assuming it could be because on loading, the country selected is "United States" and it populates a list of states but none of them is default or selected. Is there any other way to define a default value so that it doesn't show "Undefined"?
And another (but less important) problem is that when someone chooses "United States" for example, and then chooses "Arizona", if the person then changes to "Canada" as the country, the state of "Arizona" still stays but when opening the dropdown the provinces of Canada are selectable. Is there any way to return it to the default value temporarily when someone selects another country, until a province is chosen again?
My loading code is currently just:
<script>
$(document).ready(function() { $("#state").select2(); });
</script>
Select 3.*
Please see Update select2 data without rebuilding the control as this may be a duplicate. Another way is to destroy and then recreate the select2 element.
$("#dropdown").select2("destroy");
$("#dropdown").select2();
If you are having problems with resetting the state/region on country change try clearing the current value with
$("#dropdown").select2("val", "");
You can view the documentation here http://ivaynberg.github.io/select2/ that outlines nearly/all features. Select2 supports events such as change that can be used to update the subsequent dropdowns.
$("#dropdown").on("change", function(e) {});
Select 4.* Update
You can now update the data/list without rebuilding the control using:
fooBarDropdown.select2({
data: fromAccountData
});
It's common for other components to be listening to the change event, or for custom event handlers to be attached that may have side effects. Select2 does not have a custom event (like select2:update) that can be triggered other than change. You can rely on jQuery's event namespacing to limit the scope to Select2 though by triggering the *change.select2 event.
$('#state').trigger('change.select2'); // Notify only Select2 of changes
select2 has the placeholder parameter. Use that one
$("#state").select2({
placeholder: "Choose a Country"
});
Use the following script after appending your select.
$('#state').select2();
Don't use destroy.
Finally solved issue of reinitialization of select2 after ajax call.
You can call this in success function of ajax.
Note : Don't forget to replace ".selector" to your class of <select class="selector"> element.
jQuery('.select2-container').remove();
jQuery('.selector').select2({
placeholder: "Placeholder text",
allowClear: true
});
jQuery('.select2-container').css('width','100%');
Got the same problem in 11 11 19, so sorry for possible necroposting.
The only what helped was next solution:
var drop = $('#product_1'); // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2'); pick krajee attrs of our elem;
var drop_id = drop.attr('id'); // take id
settings = window[settings]; // take previous settings from window;
drop.select2(settings); // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;
It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive.
Hope, this solution will be usefull or may push you in right decision in problem fixing
The solution:
Once the content is loaded via ajax you can no longer attack generically like eg ‘.select2’. Because now other elements have this class as the span generated by select2.
So after loading ajax you need to call a method to check if select2 is already instantiated and instantiate it individually.
jQuery('select.select2').each(function (i, obj) {
if (!jQuery(obj).hasClass("select2-hidden-accessible")) {
jQuery(obj).select2();
}
});
My article about
enter link description here
Suppose you are only interested in replacing select2 data:
$('#selector').html('').select2({
data: //new data
})
Initialize again select2 by new id or class like below
when the page load
$(".mynames").select2();
call again when came by ajax after success ajax function
$(".names").select2();
I am implementing this JQuery UI multiselect from http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
When I'm trying to validate my single select dropdownbox, even if nothing's been selected and the "Please Select" is visible, it still thinks that the first item in the list is the selected one.
$("#ddlAlternativeCode option:selected").val() just gets back the value of my first item in the dropdown. I need it to be 0 or null. Can anyone help me?
You dont need to write "option:selected" in the $("#ddlAlternativeCode option:selected").val()
Try this instead:
$("#ddlAlternativeCode").val();
You should be able to see it working by adding this following alert which should show NULL if nothing is selected:
alert("value= "+$('#ddlAlternativeCode').val());
where the id is the id of the selector.
If that doesn't work, your javascript has an error somewhere.
The other way of collecting selected values with Eric's script is via the "GetChecked" method call on the API. See example here:
var array_of_checked_values = $("select").multiselect("getChecked").map(function(){
return this.value;
}).get();
I am dynamically generating some dropdowns and then allowing them some of those to be removed on board dyanmically. so that time, i have encountered an error of selection option (dropdown) elements id mismatch. something like below is.
newly added dropdowns.
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][1]" id="client_time_window_1">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
after i dynamically remove them via javascript. (lets say i am removing the second one) so then new ones will be displayed as followings,
select name="CSSAtapsClient[client_time_window_arr][0]" id="client_time_window_0">/select>
select name="CSSAtapsClient[client_time_window_arr][2]" id="client_time_window_2">/select>
select name="CSSAtapsClient[client_time_window_arr][3]" id="client_time_window_3">/select>
So now the issue i have is, the names of the dropdowns are like this, (0,2,3)
CSSAtapsClient[client_time_window_arr][0],
CSSAtapsClient[client_time_window_arr][2],
CSSAtapsClient[client_time_window_arr][3]
So this is causing an error for me and i need to reorder this name and make it be like this, (0,1,2)
CSSAtapsClient[client_time_window_arr][0]
CSSAtapsClient[client_time_window_arr][1]
CSSAtapsClient[client_time_window_arr][2]
how can i simply rename these dropdowns name attribute (from 0 to how much ever dropdows are exisiting) ? appreciate an early reply
EDIT 1
I tried this, but didnt work.
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][i]");
});
You can simply reset the values using .attr() method:
$('#tbl_dynamic_call_dates select').attr('name', function(i) {
return 'CSSAtapsClient[client_time_window_arr]['+ i +']';
});
I did this,
$('#tbl_dynamic_call_dates select').each(function(i){
$(this).attr('name',"CSSAtapsClient[client_time_window_arr][" + i + "]");
});
I have a working jQuery autocomplete being performed on the text input of a table data element, txtRow1. The text data is remote, from a mysql database, and is returned by JSON as 'value' for the text input. The returned data includes another piece of text, which, via a select event within the autocomplete, is populated to the adjacent table data element tickerRow1.
With help from the SO community, the autocomplete is now live and working on all text input elements of a dynamically created table (so txtRow1 to txtRowN). There is javascript code to create and name the table elements txtRoxN + 1 and tickerRowN + 1.
However, I have a problem with the select event for the id of tickerRowN. Because it changes every time I add a row, I don't know how to call the select event for the specific id of the table data in question.
I have done a lot of searching around but as I am new to this, the only functions I have been able to find manipulate the element data when you know the id already. This id is dynamically created and so I don't know how to build the syntax.
Thankyou for your time.
UPDATE: with huge thanks to JK, the following example works. I now know about jsFiddle and will try to use this for all further questions. The following code works for my dynamic example, but I don't know why. Sigh.
jsFiddle working example
function getRowId(acInput){
//set prefix, get row number
var rowPrefix = 'txtRow';
var rowNum = acInput.attr("id").substring((rowPrefix.length));
return rowNum;
}
$("#txtRow1").autocomplete({
source: states,
minLength: 2,
select: function(event, ui) {
var tickerRow = "#tickerRow" + getRowId($(this));
//set ticker input
$(tickerRow).val(ui.item.label);
}
});
http://jsfiddle.net/jensbits/BjqNz/