I'm using Bootstrap v3 and Codeigniter... In my app, there is two select option element, for choosing state and city. I'm using ajax and when a state is selected, populated second element with related cities:
$('#state').change(function(){
var state_id = $('#state').val();
if(state_id != ""){
var post_url = "<?php echo base_url(); ?>student/get_cities/" + state_id;
$.ajax({
type: "POST",
url: post_url,
cache: true,
success: function(cities){ //calling the response json array 'cities'
$('#city').empty();
$.each(cities, function(id, city){
$('#city').append($("<option></option>").val(id).text(city));
}); //each
}
}); //ajax
}
}); //change
everything is good, just bootstrap select option element has a bad view on other browsers! (it's good just on chrome). so I decide to use bootstrap-select plugin: Bootstrap-Select
My question is: How could I populate second select option for cities? In fact, It will be populate, but so the bootstrap-select using dropdown, I must also populate it.
thanks for attention...
EDITED:
<select class="form-control selectpicker" name="state" id="state">
<!--in a foreach loop, echo all states with the proper value-->
</select>
<select class="form-control selectpicker" name="city" id="city">
</select>
SOLVED: I find the solution... simply add one line after populating select element!
$('.selectpicker').selectpicker('refresh');
As I understand your question the city select will populate from the AJAX but it loses the selectpicker functionality?
Maybe that is due to the $('#city').empty() line?
If so: then could you try starting again with a new select? E.g.
replace: $('#city').empty();
with this code
$('#city').remove();
$('#state').after( $('<select></select>').addClass('form-control selectpicker').attr({'id' : 'city', 'name' : 'city'}) );
//do your ajax stuff and add the options
$('#city').selectpicker(); //initialise it
*untested
(If the above works it may be overkill and you could simply solve the problem by re-initialising the city select after re-loading it. I.e you'd just need the $('#city').selectpicker(); line).
Related
Consider that I have the following select tag:
<select id="select_val">
<option>This is first</option>
<option>This is second</option>
</select>
Now what I want is , I want the select to be present however we should not be able to change it further.
e.g if he selects option two i.e This is second, he cannot change it further. How can i do that using jquery. Thanks in advance
$('#select_val').change(function(){
$(this).prop('disabled', true);
})
Edit after comment:
If You want pass selected value and keep selection disabled, there are several solutions. Now it depends if You use AJAX or just simple form submit.
For AJAX You can do it like that:
$('form').submit(functiom(){
$('#select_val').prop('disabled', false);
var data = $(this).serialize();
$('#select_val').prop('disabled', true);
$.ajax({
url : 'some_url',
data : data
// ... other parameters here
});
});
If it's simple form submit then I wouldn't toggle disabled to off as user can stop sending form by pressing escape key and then change selection. Then another approach could be create hidden input like:
$('form').submit(functiom(){
var select = $('#select_val');
$(this).append('<input type="hidden" name="'+ select[0].name +'" value="'+ select.val() +'">');
});
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();
On my site, the user selects a person, and when the selection is made, it populates demographics about that patient below, but gives the user the options to change each demographic value. I have an html select statement for a "Prep RN" that is populated from a table of RNs when the form is loaded, but when I select a patient, I can't get it to change the select to the RN that is stored in the database and is contained in the list:
$.ajax({
url: 'php/pullselectedpatient.php',
type: 'POST',
dataType: 'json',
cache: false,
data: {Patient_UID: tempPatient_UID},
success: function(data) {
if (data.Prep_RN == 'Unassigned') {
//if unassigned, set option to unassigned
$('#selectpreprn').val('Unassigned');
} else {
//if assigned, change to selected RN
$('#selectpreprn').val(data.Prep_RN);
},
error: function() {
alert("ajax call failed.");
}
});
This code fills the option list successfully, but in case it's part of the problem, here it is:
<label for='selectpreprn'>Prep RN: </label>
<select id="selectpreprn">
<option value="empty"></option>
<?php
require('php/pullrns.php');
//loop and add the patients to the drop down list
foreach($result_rns->fetch_all(MYSQLI_ASSOC) as $row) {
echo "<option value='", $row['RN_UID'], "'>", $row['RN_UID'], "</option>";
}
?>
</select>
This results with the select filled with a 'blank', 'Unassigned', and then 3 names to choose from.
Also, this is my first time posting to this site (which is amazingly helpful), so I hope I provided everything. I have spent at least 3 hours trying different things to make this work.
To reiterate, the problem is that it doesn't select the option in the select tag when the patient is selected. It just stays blank.
This code works as intended, the issue was further down my page where I was inadvertently overwriting this selector. I copied and pasted similar code, and it got me in trouble =(
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;
}
I have a select input with the following code:
<select name="color" id="color" multiple class="form-control chzn-select" tabindex="8" onchange="autosave(this.id,this.value)">
It is successfully sending the function ID and select value, but seeing as one can select multiple items, it's having an issue. I can select up to 3 items without a problem, but attempting to select a 4th is causing it to pass the value of the first selected item. Not the most recently selected item. Here's the function, which sends other information such as title and date (both text inputs):
function autosave(inputid,values) {
var dataObj = {};
dataObj[inputid] = values;
$.ajax({
type: "POST",
url: "save.php",
data: dataObj,
success: function(msg) {
$('#autosavenotify').text(msg);
console.log('success');
}
})
}
HTML wise I am using Bootstrap3 if that makes a difference and here's how I'm populating the select options:
<?php
$colors = array('Red','Blue','Yellow','Purple','Green','Orange');
foreach($colors as $c) {
$selected = '';
if(in_array($c, $_SESSION['array']['colors'])) {
$selected = 'selected';
}
echo '<option value="'.$c.'" '.$selected.'>'.$c.'</option>';
}
?>
Any ideas why this might be happening? My save.php page is placing all items successfully within the array, the ajax is just sending the incorrect value for some reason.
Because you're already using jQuery, you'd probably be better off just using $(this).val( ) to get the selected options from your select. Here's a fiddle I came up with using your provided code: http://jsfiddle.net/y7NfF/1/
Another route you might consider taking would be using jQuery's .serialize() or .serializeArray() function to get all values of your form when submitting the data through ajax. However, if you want to do one element at a time, your method works just fine.
Here are a couple of links to those functions:
http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/