Reload div with Select2 field using Ajax or JQuery [duplicate] - javascript

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();

Related

Display number of options selected as soon as they are selected using a multiple choice select2

So, I have this multiple choice select2 that gets its options via database query and I wanted to show in an input the number of options that are selected. However, I wanted to do it as soon as they are selected and I don't know how to do it. For example, if I choose 2 options and then, later, I decide to add one more, I want the input to change to 3 options selected. Any help is appreciated and if you have other ideas like how I can do similar stuff but not like how I described it your help is appreciated too. Thanks
<select name="select_areas_educ_form" id="select_areas_educ_form" class="form-control js-example-tokenizer" multiple="multiple">
<?php foreach ($areas_educacao as $area)
{
echo '<option value="'.$area['id_areaeducacao'].'">'.$area['cod'].' - '.$area['designacao'].'</option>';
}
?>
</select>
So, its much more simple than what I expected, so if anyone need the answer I'll leave it here. You just basically need to add an "onChange" in your select that calls a function. The function will count the number of options selected via jquery and after, change the placeholder of the input. Its very simple and now I can't explain how I didn't think of this before
function opcoes_select_areas_educ_form()
{
var n_opcoes = $("#select_areas_educ_form :selected").length;
document.getElementById("total_areas").placeholder = n_opcoes;
}

Get currently selected value in editable select box

I have used editable select Jquery plugin ,now the problem is i want the currently selected value of editable select control with out on change or other event
link to Editable select
I have tried following till now but no success
$('#customer_name').find('li.selected').value()
$('#customer_name').siblings('.es-list').find('li.selected').value()
$("#customer_name").val();
HTML
<select id="customer_name" name="customer_name" class="form-control">
<?php
foreach($customers as $customer){
echo "<option value='".$customer['cust_id']."'>".$customer['cust_name']." </option>";
}//foreach
?>
</select>
$('#customer_name').editableSelect();
I have dome some R&D regarding this question and I have found something which helps me to achieve the goal. So, I am sharing the Jquery code with the Link so that you can get more information.
Jquery code for getting the selected value:
$('#onselect')
.editableSelect()
.on('select.editable-select', function (e, li) {
console.log('Seletced Value: ');
console.log(li.val() + '. ' + li.text());
});
Ref. Website Jquery Editable Select Example
Thanks.
Try this
const x = $('#customer_name').attr('value')
this should work.
if this doesn't work, then your HTML element doesn't have an attribute called value, try adding a value & id to any HTML element then do $(id).attr('value') and you'll get the value attribute
I have read the docs but i could't find any solution so what i have done is stored the value of editable select in hidden filed for the first time and when user change the value then i have jquery to update the value .
if any one has solution please mention

How to force selecting first item when using Kendo MVVM Dropdownlist

function GenericSelectFirst(e){
// This function is called without any errors, I have verified it
e.sender.select(0);
}
<select class="full-width"
name="..."
data-bind="source: ..., value: ..., visible: ..., events:{dataBound: Function.GenericSelectFirst}"
data-role="dropdownlist"
data-value-field="..."
data-text-field="..."
data-value-primitive="true"
data-auto-bind="true"
required="required"
>
</select>
I did not think that it is that hard to achieve such a common easy scenario, but I have a Kendo DropDownList which initialize using MVVM style, and it is binding a remote datasource.
What I want to achieve is that, once the remote datasource is ready and bound to the widget, the first option is selected by default (and of course the value of the first item should be bound to the view model)
I tried to do it directly with the above code, which binds an dataBound event to the widget, and select the first item when it fires. The callback method has been called without errors, but the widget never select the first option but keep selecting the first default "empty" option.
What did I do wrong and how can I fix it? Any advice is appreciated!
Wich Kendo version are you using? If latest, remember that since
V. Q1 2015 , In order to match the Html Select behavior better and solve some issues related to MVVM value binding, the dropdownlist now allows to clear its value (deselect the selected item). This will introduce the following breaking changes:
The widget will not select the first item, when its selected index is -1
The widget will not select the first item, when the selected value is not present in the data source.
Long story short, If someone wants to get the previous behavior, then he/she will need to select first item manually:
dataBound: function() {
if (this.select() === -1) { //check whether any item is selected
this.select(0);
this.trigger("change");
}
}

Can't programmatically select option using Select2

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

Update field with jquery don't update observable

I want to say hello to the stackoverflow community.
I've just started using knockout a few days ago.
Right know I'm using it to make a dynamic menu builder for a CMS I'm working on.
Here is the code: http://jsfiddle.net/dnlgmzddr/HcRqn/
The problem is that when I choose an element from the select box, the input field update as I expect, but the observable doesn't reflect the change. Because of that, the add button is not enabled.
What am I missing? How can I fix it?
Thank you.
When you populate the url field, you would need to trigger the change event to get the observable to be upated. So, you could do:
$("#url").val('/pages/' + id).change();
Another option though that is more in the Knockout spirit is to use a binding on your select. In this case, you would likely want to populate an observable with that value, then use a manual subscription to default the formatted value into the input field.
this.itemUrl = ko.observable();
this.selectedUrl = ko.observable();
this.selectedUrl.subscribe(function(newValue) {
if (newValue) {
this.itemUrl("/pages/" + newValue);
}
}, this);
Then, bind your select to selectedUrl:
<select id="pagedList" data-bind="value: selectedUrl">
<option value=""><option>
<option value="test">Test</option>
</select>
Here is a sample: http://jsfiddle.net/rniemeyer/HcRqn/21/
You could also eliminate the extra observable and manual subscription if the "value" of your options was the url.
I can't see anywhere in your code where you are actually enabling the button when a field is selected. So I might be missing something, but just enable the button on change. Like the following:
function LoadMenu() {
$("#pagedList").change(function () {
var id = $(this).val();
$("#url").val('/pages/' + id);
// remove the disabled attribute here
$('button.space').removeAttr('disabled');
});
}

Categories