Issue with Select after prepending option - javascript

I am creating a select dropdown on the fly using PHP to get the data and build the options. Then I am using Ajax to fetch this (with the following lines) and prepend an additional option.
All of this works as intended, my only issue is that in the dropdown it always selects the second option which is the first one from my PHP / Ajax call but not the option that I am prepending before that.
I also tried changing selected to selected='selected' but that doesnt make a difference.
What am I doing wrong here or how this can be changed in jQuery / JS so that it selects the prepended option ?
Note: I am using this inside a Bootstrap 3 modal.
My JS (shortened):
var levelMain = $(this).closest('tr').find('.levelMain').text();
// ...
$.ajax({
url: 'ajax.php?node=fetchNav1',
cache: false,
error:function(err) {
alert(err.statusText);
},
success:function(html) {
$('#divLevelMain').html(html);
$("#levelMain").prepend("<option value='' selected>" + levelMain + "</option>");
}
});
The Select is a standard HTML select that looks as follows:
<select class="form-control" id="levelMain">
<option value="some value">some text</option>
// ...
</select>

Are You making sure you unselect all the other Options in that Select tag?
$('#levelMain').children('option').removeAttr('selected');
$('$levelMain').prepend("<option...</option>");
or it may be that you should add the selected attribute after appending to make sure it is updated properly in DOM
var element = $("<option...</option>");
$('$levelMain').prepend(element);
$('#levelMain').children('option').removeAttr('selected');
element.attr('selected','selected');
cause the browser will default to the first one selected, then when you prepend it will stay selected thus the second one will be selected rather then the first one.

It should be pretty easy to update the selectedIndex of the <select> element with the following:
success:function(html) {
$('#divLevelMain').html(html);
$("#levelMain").prepend("<option value=''>" + levelMain + "</option>");
$("#levelMain")[0].selectedIndex = 0;
}

Related

Why selected value of select gets change in dynamic dropdown?

I have some code in which two select boxes are present. One select is dynamically changing its value with respect to the first one. The first select box is this in which some values are coming from backend using PHP.
<select class="form-control" name="tsm_id" id="tsm_id">
<option value=""><b>SELECT TSM</b></option>
<?php echo fill_year($connect); ?>
</select>
A second select box is this which is dependent on the first one. When any value in the first box is selected this select box change its value dynamically.
<select class="form-control" name="sr_id" id="sr_id">
<option value="" selected>SELECT SR</option></select>
But the problem is this that when I select any value in first select box then the selected value SELECT SR disappears and only values from backend comes there. I want that if anyone select value from first select box then SELECT SR remains there as selected value the rest values comes below that. I am using javascript code to append those options.
$(document).ready(function(){
$('#tsm_id').change(function(){
var tsm_id = $(this).val();
$.ajax({
url:"http://localhost/salesforce/fetch_sr.php",
method:"GET",
data:{tsm_id:tsm_id},
dataType:"json",
success:function(data){
// var data=JSON.stringify(data);
$('#sr_id').html('');
for (var i in data)
{
$("#sr_id").append("<option value="+data[i].employee_id+">"+data[i].employee_name+"</option>");
}
}
});
});
});
Can anyone tell me what am I doing wrong in this.
What i want is if someone selects value from the first select box then second select box remains same as in image with selected value set to SELECT SR and the options should be appended below it.
I want something like this:
I don't want like this if I am selecting a value from the first select box then the second select box displaying options, not the default value.
Presently I am getting like this:
$('#sr_id').html('');
This is removing the default option on ajax success.
You might want to use:
$('#sr_id').html('<option value="" selected>SELECT SR</option>');
You're currently removing all options in your ajax callback before you loop out the new ones.
If you change
$('#sr_id').html('');
to
$('#sr_id').html('<option value="" selected>SELECT SR</option>');
that option will always be the first (and selected) value.

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

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

Changing "Selected" Attribute of a Dropdown-List does not work properly

I have a dropdown-list in a form, whichs onchange event gets listenend by jquery and leads to an AJAX call. Afterwards Jquery just sets/removes the selected attribute depending on the answere of the server:
$( document ).ready(function(){
$("#user_select").on("change", function(){
var value = $("#user_select").val();
$.ajax({
url: "../ajax/change_permission.php",
method: "POST",
data: { user_id: value }
}).done(function(data){
var i = 0;
while(i < 4){
$("#perm_"+i).attr("selected", false);
$("#perm_"+i).removeClass("active_perm");
i++;
}
$("#perm_"+data).attr("selected", true);
$("#perm_"+data).addClass("active_perm");
});
});
});
In my user_select dropdown are my users whose permission should be shown if I select it.
The form (where the select should be set to) looks like that:
<select id="user_permission" class="form-control">
<option id="perm_0" value="0">Berechtigungsstufe</option>
<option id="perm_1" value="1">Administrator</option>
<option id="perm_2" value="2">Super-User</option>
<option id="perm_3" value="3">User</option>
</select>
The problem now is that if a option has already been selected once, it cannot be set to active again, or better said, the selected tag still gets aplied to the option, but it isn't changed anymore (just stays on option zero). After i've selected every option once, the select looks like that:
<select id="user_permission" class="form-control">
<option id="perm_0" value="0">Berechtigungsstufe</option>
<option id="perm_1" value="1" class="">Administrator</option>
<option id="perm_2" value="2" class="">Super-User</option>
<option id="perm_3" value="3" class="">User</option>
</select>
The selected="selected" attribute still gets applied to the option, but the selected option won't be changed (the display isn't changed) anymore. Already thought it is bugging because of the empty class tag, but it changes nothing if i remove it.
Anyone having an idea what may cause that problem?
EDIT: All in all it is that JSfiddle just without the Random values :p
EDIT ANSWERE: The Jquery ".attr" does not work properly in Firefox 42.0. Instead i've used ".prop", what works correctly.
Jquery has two different functions attr() and prop(). Those two use for different purposes. attr is for all attributes. prop is for properties. In your case dropdown element "selected" is not a attribute. It is a property. Therefore you should use prop function as below.
$("#perm_"+data).prop("selected", true);
Note: However some modern browser works for both, but for cross browser compatibility always try to use correct one.
Why you use options under select you can directly use $("#user_permission").val(1)

HTML Select Option Value Not Updating

I have a HTML form with the following select element in it:
<select class="form-control" onchange="$('form#filter').submit()" id="sort" name="sort">
<option value="0" selected="selected">A - Z</option>
<option value="1">Z - A</option>
</select>
The issue is that when I select a different option, the HTML doesn't update and set the option I chose as the selected option.
I have absolutely no idea why it isn't updating and I've been at it for hours now.
This is the function that is bound to the submit event on the form in case you need it:
$("form#filter").on("submit", function(evt)
{
var form = $(this);
var target = $("div#bands");
var url = form.attr("action") + "/" + form.find('option[selected]').val();
console.log(url);
$.get(url).done(function(data)
{
target.html(data);
});
evt.preventDefault();
});
Change
form.find("option[selected]").val()
to
form.find("option:selected").val()
or:
form.find("select").val()
or:
$("#sort").val()
The selector option[selected] doesn't find the option that's currently selected, it finds the option that has the selected attribute in the DOM (this is normally the one with the selected attribute in the HTML, although it's possible to change it using Javascript).
The accepted answer is incorrect. Here is a correct solution (tested on latest JQuery and Bootstrap at time of writing):
$("#mySelect").find("option:selected").val();
Thanks to Barmar for the inspiration, though only 1 of the 4 suggestions works, and only by accident. But I adapted that to log out the correct value attribute for the currently selected option. (The selected state of the initial option does not update when using the dropdown, see Chris O'Kelly's comment.)

Add or remove dropdown elements from the javascript or jquery

I have dropdownlist whose value is filled using the value of the other drop down. The problem here is that i need to bind the value of the second when the value of the first changes. I need to do it from the javascript.
Only thing i need to do is remove and add the select options in the second dropdown as the first dropdown changes.
How can i do this?
Thanks in advance.
Not too sure exactly what you want with the limited information provided but here is a solution that I think you are looking for:
HTML:
<select id="primary">
<option value="one">One</option>
<option value="two">Two</option>
</select>
<select id="secondary"></select>
jQuery:
var opts = {
'one':['a','b','c'],
'two':['d','e','f']
};
$('#primary').change(function(){
var select = [];
$.each(opts[this.value], function(k, v){
select.push('<option>'+ v +'</option>');
});
$('#secondary').html(select.join(''));
});
Demo: http://jsfiddle.net/28TQZ/
$("#dropdownlist1").change(function () {
var selected = $("#dropdownlist1 option:selected");
//clear
$("#dropdownlist2").html("");
$("#dropdownlist2").append($("<option/>").text(selected.text()).val(selected.val()));
})
Create all the drop downs you need, but only add options to the first one. The next ones only have a "default" value.
On selecting the first drop down, you use jQuery to get the values for the second drop down, based on the value selected in the first drop down:
$.post('ajax/aj_populate2nddropdown.php', $("#firstdropdown").val(), function(result) {
$('div.placedaround2nddropdown').html(result);
});
The file ajax/aj_populate2nddropdown.php collects the values of the second drop down, and returns them, inserted as options into the dropdown.
One simple way to do it is to just have a main dropdown and a bunch of secondary dropdowns that start hidden. when you choose something from the first, then you unhide the related second one
Try this If you are trying at client side
Replace your controls with asp.net server controls

Categories