Dynamic populating dropdown using jquery/ajax - javascript

I am trying to dynamically populat the drop down list based on the selected value of first list.
NOTE: Both dropdowns are multiple selection dropdown:
This is the code for my dropdowns:
<select id="dis" name="dis[]" onChange="AjaxFunction();" class="form-control selectpicker show-menu-arrow" multiple title="Select a City or Division">
// my discrictes goes here
</select>
<select id="zone" name="zone[]" class="form-control show-menu-arrow" multiple title="Choose Educational Zone" ></select>
To do this I found AjaxFunction() javascript function. And its as below:
function AjaxFunction(){
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if(httpxml.readyState==4) {
var myarray = JSON.parse(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.getElementById('s2').length-1;j>=0;j--) {
document.getElementById('s2').remove(j);
}
for (i=0;i<myarray.data.length;i++) {
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].name_si;
optn.value = myarray.data[i].zone_id;
document.getElementById('s2').options.add(optn);
}
}
}
var str='';
var s1ar=document.getElementById('s1');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
//alert (s1ar);
var str=str.slice(0,str.length -1); // remove the last coma from string
//alert(str);
//alert(str);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
//alert(url);
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
//httpxml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpxml.setHeader('Content-type', 'application/json');
httpxml.send(null);
}
My question is, now I need to convert above function to jquery, because I am looking for a jQuery/Ajax solution for this:
This is how I tried it using jQuery:
$('#dis').on('change',function() {
var str='';
var s1ar=document.getElementById('dis');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
var str=str.slice(0,str.length -1);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function(data) {
$('#zone').empty();
$('#zone').append("<option value=''>- Select Zone-</option>");
$.each(data, function(i,item){
var selecting;
if (selected === data[i].id) {
selecting = ' selected="selected"';
} else {
selecting = '';
}
$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
});
},
complete: function() {}
});
});
But is not working for me. Can anybody help me out to figure this out?
Thank you

The code is fine, I am getting error with "selected" is undefined
You can see if(selected === data[i].id) here "selected" variable is not assigned to selected value from first dropdown.
also you need to remove onChange="AjaxFunction();" from first dropdown because now your are using jQuery
Check below code:
$(document).ready(function(){
$('#dis').on('change',function() {
var str='';
var s1ar=document.getElementById('dis');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
var str=str.slice(0,str.length -1);
var url="dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function(data) {
$('#zone').empty();
$('#zone').append("<option value=''>- Select Zone-</option>");
$.each(data, function(i,item){
var selecting='';
if ($('#dis').val().findIndex(x => x==data[i].id)>=0) {
selecting = ' selected="selected"';
} else {
selecting = '';
}
$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
});
},
complete: function() {}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dis" class="form-control selectpicker show-menu-arrow" multiple title="Select a City or Division">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select id="zone" class="form-control show-menu-arrow" multiple title="Choose Educational Zone" ></select>
The result is some like this:
jSon file value is :
[{
"id": 1,
"name": "New"
},
{
"id": 2,
"name": "Open"
},
{
"id": 3,
"name": "Close"
}
]

Related

How to set value programmatically to Select2 jQuery & ASP .Net Core

I'm working on a ASP .Net Core project where for the first time I'm using Select2.
I have one page where I'm passing the ID's that I need by ViewModel like this:
Controller:
public async Task<IActionResult> MyPage()
{
var model = new MyViewModel()
{
selectedUSerId = 1,
selectedEmployeeId =1
};
return View(model);
}
View:
#model MyViewModel
<select class="form-select" id="User" name="User" data-url="#Url.Action("MyUserAction","MyUserController")" data-placeholder="#Localizer["SelectUser"].Value">
<option></option>
</select>
<select class="form-select" id="Employee" name="Employee" data-url="#Url.Action("MyEmployee","MyEmployeeController")" data-placeholder="#Localizer["SelectUser"].Value">
<option></option>
</select>
#section Scripts{
<script type="text/javascript">
var userId = "#Model.selectedUSerId";
var emplyeeId = "#Model.selectedEmployeeId";
$(document).ready(function () {
$('select').each(function () {
InitSelect2(this.id);
});
if(userId){
$('#User').val(userId).trigger('change');
}
if(emplyeeId){
$('#User').val(emplyeeId).trigger('change');
}
});
function InitSelect2(selector, selectedId = 0) {
var url = $("#" + selector).data('url');
var placeholder = $("#" + selector).data('placeholder');
const type = "POST";
const dataType = "json";
if (!url) {
console.error("Selector: " + selector + " Unspecified URL");
return;
}
if (placeholder === "") {
console.error("Selector: " + selector + " Unspecified Placeholder");
return;
}
try {
$("#" + selector).select2({
theme: "bootstrap-5",
width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
placeholder: placeholder,
allowClear: true,
minimumInputLength: 3,
ajax: {
url: url,
type: type,
dataType: dataType,
delay: 250,
data: function (params) {
var query = {
id: selectedId,
searchFullName: params.term,
}
return query;
},
processResults: function (data) {
console.log(data)
return {
results: data.results
};
},
}
})
} catch (ex) {
console.error(ex);
}
}
</script>
}
So far it works perfectly.
But when I try to do:
$('#User').val(userId).trigger('change'); or
$('#Employee').val(emplyeeId ).trigger('change');
nothing happened.
I think its gonna work only when I retrieve the data the first time when I click the drop donw list, instead of doing it every time when it is clicked.
In that way I will have the <option>s and I can use the jQuery to select the <option> by Id.
I don't like to follow this approach, becouse the data should be load and setted dynamically. Theres no another way to do it?
If you want to do something only when first time the selected value is changed,you can try to use a js variable,change the value of it when first time the selected value is changed.Here is a sample,only when first time the selected value is changed,alert(1) will be called.
var UserCount = 0;
var EmplyeeCount = 0;
$('#User').change(function() {
if (UserCount == 0) {
UserCount++;
alert(1);
}
});
$('#Employee').change(function() {
if (EmplyeeCount == 0) {
EmplyeeCount++;
alert(1);
}
});

Event Delegation Issue jQuery

I have the below code, the first HTML snippet is loaded on the initial page load, then when the span with id flag is clicked the javascript will load the second HTML snippet into a hidden div on the webpage.
Now this hidden div has a select drop down box which when changed the javascript should make another AJAX call but $("#overlay #innerWrapper #country").on('change', function() { is never called.
I'm sure it's an event delegation issue but can't seem to see where I'm going wrong!?
Javascript
$("#topBar").on("click", "#flag", function(e) {
e.preventDefault();
var data = {};
$("#overlay").css("display", "inline");
// Country Change
$("#overlay #innerWrapper #country").on('change', function() {
var country = $(this).val();
ajaxCall(country);
});
ajaxCall(data);
e.stopPropagation();
});
Loaded on page load (snippet 1)
<div id="topBar">
<span id="flag" class="flag-icon"></span>
</div>
Loaded via a AJAX query (snippet 2)
<div id="innerWrapper">
<div id="title">Select Country</div>
<span id="flag" class="flag-icon"></span>
<select id="country" name="country">
<option value="fr" selected="selected"> France</option>
<option value="de"> Germany</option>
</select>
</div>
Update 1:
$("#innerWrapper").on('change', '#country', function() {
alert('1');
var country = $(this).val();
ajaxCall(country);
});
$("#topBar").on("click", "#flag", function(e) {
e.preventDefault();
var data = {};
$("#overlay").css("display", "inline");
ajaxCall(data);
e.stopPropagation();
});
function ajaxCall(element, callId, dataIn)
{
var limit;
var data;
if ($(element).data("limit")) {
limit = $(element).data("limit");
data = {id: callId, limit: limit, data: dataIn};
}
data = {id: callId, data: dataIn, element: element};
$.ajax(
{
type: "POST",
url: "ajax.php",
data: data,
beforeSend: function ()
{
if (element != 'ignore') {
$(element).append( "<div class=\"loading\"></div>");
}
},
success: function (data)
{
if (element != 'ignore') {
$(element).html(data);
} else {
location.reload(true);
}
},
complete: function ()
{
if (element != 'ignore') {
$(element).siblings(".loading").remove();
}
},
error: function (jqXHR)
{
$(element).html(jqXHR.status + " - " + jqXHR.statusText);
}
});
}

Jquery get values from select boxes and make AJAX call

I have multiple select boxes, where I want to get the value of each selected option and make an AJAX call based on the selected options. How can I achieve that?
I have this so far:
$('select[name="restaurant_chosen"]').on('change', function() {
var restaurant_id = $(this).val();
});
$('select[name="date_chosen"]').on('change', function() {
var date_chosen = $(this).val();
});
$.ajax({
type: 'GET',
url: '/api/' + restaurant_id + '/' + date_chosen +
success: function(data) {
console.log(data)
},
error: function(data){
console.log('error')
}
});
the 2 variables restaurant_id and date_chosen I get the error not defined. What am I doing wrong?
function sendToServer(values, onSuccess, onError){
var restaurant_id, date_chosen;
//here fill restaurant_id and date_chosen using values
$.ajax({
type: 'GET',
url: '/api/' + restaurant_id + '/' + date_chosen, //replace the plus by a comma
success: function(data) {
onSuccess(data);
},
error: function(data){
onSuccess(data);
}
});
}
$('select').on('change', function() {
var values = [];
$('select').each(function(index){
v = $(this).val();
n = $(this).attr("name");
values.push( {"name":n, "value":v} );
});
console.log("values: ", values);
sendToServer(values,
function(data){
console.log(data);
},
function(data){
console.log('error', data);
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="brand">
<option value="volvo">Volvo</option>
<option value="audi">Audi</option>
</select>
<select name="color">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
And that is how it should be. You're declaring your variable within a private function context, which you cannot (and must not) access from the outside.
Simple solution, move the declaration of your two variable out of the onchange event handlers (make it more global).
var restaurant_id;
date_chosen;
$('select[name="date_chosen"]').on('change', function() {
date_chosen = $(this).val(); // skip the var here
});

Internet Explorer is not getting all data from xml file in dropdown menu

This Javascript code works fine in chrome and Firefox, but it only shows the first item of the "School/College" dropdown box in Internet Explorer. Do you guys see anything IE wouldn't like in this code?
HTML:
<label>School/College:</label>
<select class='mktFormSelect mktFReq' name="School_College_RFI__c_contact" id="School_College_RFI__c_contact" size='1' tabIndex='19'>
<option value='' selected='selected'></option>
</select>
<label>Academic Program:</label>
<select class='mktFormSelect mktFReq' name="Academic_Program_RFI__c" id="Academic_Program_RFI__c" size='1' tabIndex='20'>
<option value='' selected='selected'></option></select>
<label>Academic Career:</label>
<select class='mktFormSelect mktFReq' name="Academic_Career_RFI__c" id="Academic_Career_RFI__c" size='1' tabIndex='21'>
<option value='' selected='selected'></option>
</select>
<label>Academic Plan of Interest:</label>
<select class='mktFormSelect mktFReq' name="Academic_Plan_of_Interest_RFI__c" id="Academic_Plan_of_Interest_RFI__c" size='1' tabIndex='22'>
<option value='' selected='selected'></option>
</select>
JavaScript
<script type="text/javascript" id='autocomplete'>
<!-- Dropdowns -->
$jQ(document).ready(function() {
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ('#School_College_RFI__c_contact option').remove();
$jQ('#School_College_RFI__c_contact').append('<option>Please Select</option>');
$jQ(xmlResponse).find('school').each(function(){
sc = $jQ(this).find('sname').text();
$jQ('#School_College_RFI__c_contact').append('<option value="'+sc+'" >'+sc+'</option>');
console.log(sc);
});
}
});
$jQ('#School_College_RFI__c_contact').change(function(){
var ap;
var college = $jQ(this).val();
$jQ('#Academic_Program_RFI__c option').remove();
$jQ('#Academic_Career_RFI__c option').remove();
$jQ('#Academic_Plan_of_Interest_RFI__c option').remove();
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ(xmlResponse).find('sname').each(function(){
if($jQ(this).text() == college){
$jQ('#Academic_Program_RFI__c').append('<option>Please Select</option>');
$jQ(this).siblings('academic_program').each(function(){
ap = $jQ(this).find('pname').text();
$jQ('#Academic_Program_RFI__c').append('<option value="'+ap+'" >'+ap+'</option>');
});
}
});
}
});
}).trigger('change');
$jQ('#Academic_Program_RFI__c').change(function(){
var ac;
var academic_program = $jQ(this).val();
$jQ('#Academic_Career_RFI__c option').remove();
$jQ('#Academic_Plan_of_Interest_RFI__c option').remove();
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ(xmlResponse).find('pname').each(function(){
if($jQ(this).text() == academic_program){
$jQ('#Academic_Career_RFI__c').append('<option>Please Select</option>');
$jQ(this).siblings('academic_career').each(function(){
ac = $jQ(this).find('cname').text();
$jQ('#Academic_Career_RFI__c').append('<option value="'+ac+'" >'+ac+'</option>');
});
}
});
}
});
}).trigger('change');
$jQ('#Academic_Career_RFI__c').change(function(){
var ai;
var academic_career = $jQ(this).val();
$jQ('#Academic_Plan_of_Interest_RFI__c option').remove();
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ(xmlResponse).find('cname').each(function(){
if($jQ(this).text() == academic_career){
$jQ('#Academic_Plan_of_Interest_RFI__c').append('<option>Please Select</option>');
$jQ(this).siblings('academic_plan_of_interest').children('value').each(function(){
ai = $jQ(this).text();
$jQ('#Academic_Plan_of_Interest_RFI__c').append('<option value="'+ai+'" >'+ai+'</option>');
});
}
});
}
});
}).trigger('change');
});
</script>
Yes. There have been some inherent bugs with IE when it comes to constructing drop downs dynamically. I think it has to do with ability of IE to draw the dropdown. You can fix this two ways:
Set the drop down css property of display to none, construct the drop down and then remove the display property.
Force IE to construct the select again with a code like $("select").width($("select").width());
Read more about this issue here:
https://www.getharvest.com/blog/2009/12/dropdown-problems-on-internet-explorer/
<select> only shows first char of selected option
EDIT: Here's an example
OPTION 1:
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ('#School_College_RFI__c_contact option').remove();
$jQ('#School_College_RFI__c_contact').hide();
$jQ('#School_College_RFI__c_contact').append('<option>Please Select</option>');
$jQ(xmlResponse).find('school').each(function(){
sc = $jQ(this).find('sname').text();
$jQ('#School_College_RFI__c_contact').append('<option value="'+sc+'" >'+sc+'</option>');
console.log(sc);
});
$jQ('#School_College_RFI__c_contact').show();
}
});
OPTION 2:
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
$jQ('#School_College_RFI__c_contact option').remove();
$jQ('#School_College_RFI__c_contact').append('<option>Please Select</option>');
$jQ(xmlResponse).find('school').each(function(){
sc = $jQ(this).find('sname').text();
$jQ('#School_College_RFI__c_contact').append('<option value="'+sc+'" >'+sc+'</option>');
console.log(sc);
});
$jQ('#School_College_RFI__c_contact').width($jQ('#School_College_RFI__c_contact').width());
}
});
Note: Not tested. Assuming the code works fine in Firefox and Chrome (as OP said)
This is what worked for me. I had to practically change the entire code:
window.onload = function () {
if (window.XMLHttpRequest) {
my_xml = new XMLHttpRequest();
} else {
my_xml = new ActiveXObject("Microsoft.XMLHTTP");
}
/////////////////////////////
my_xml.open("GET", 'http://go.miami.edu/rs/universityofmiami/images/Recruitment_Profile_Mapping_Undergraduate_1014.xml', false);
my_xml.send();
xml_str = my_xml.responseXML;
var x = xml_str.getElementsByTagName("sname");
var min = 12,
max = 100,
select = document.getElementById('School_College_RFI__c_contact');
for (i = 0; i < x.length; i++) {
var opt = document.createElement('option');
opt.value = x[i].childNodes[0].nodeValue;
opt.innerHTML = x[i].childNodes[0].nodeValue;
select.appendChild(opt);
}
};

Issue not having a selected default option while populating select with ajax

I'm having a problem not being able to have a default selected option when i fill the select box with ajax call, i have the value, but not a default one, I want that the default one will be the first value i get from the call;
my HTML is (we will work on select2):
<div class="containerdiv">
<select class="select1" name="dettaglio1">
</select> <select class="select2" name="dettaglio2">
</select> <select class="select3" name="dettaglio3">
</select>
</div>
while the ajax call is that (Comments are for you):
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
and my html after the call is(F12) :
<div id="select-4-button" class="ui-btn ui-icon-carat-d ui-btn-icon-right ui-corner-all ui-shadow">
<span class="select2"> </span>
<select class="select2" name="dettaglio2">
<option value="0">option1</option>
<option value="1">option2</option>
<option value="2">option3</option>
<option value="3">option4</option
><option value="4">option5</option>
</select></div>
Is the problem on span element? and why it's blank ?
Select the default value once all the options are loaded. Check below
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('select[name=dettaglio2]').val($('select[name=dettaglio2] option:first').val());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
$(".select2")[0].selectedIndex = 0;
You should try this when your select tag is already populated/.
Thank to Pugazh I modified his answer and came to this working solution:
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
the full code:
loadEvento : function() {
$select2 = $('.select2');
luoghi.saveLuogo(); //dont care about
$
.ajax({
url : 'http://localhost:8080/Redman-Mock-Services/services/comboevento',
dataType : 'json',
// data: JSON.stringify(opzioniSelezionate.luogo),
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$("#select-4-button").children("span").html($('select[name=dettaglio2] option:first').text());
},
error : function(err) {
$select2.html('<option id="0">nessun dato disponibile</option>');
console.log(err);
}
});
}
I answered because is more clear the solution, but thumbs up his answer and comments that helped me.
(I've thumbed up everyone that helped, thanks a lot) ;)
Use following once your options loaded :
$('.select2 option:eq(1)').prop('selected', true)
Here 1 is index.you can set default value by index easily.
Change your success part to below code:
success : function(data) {
console.log(data);
$select2.html('');
// SETTING 1st value as selected
var first_iteration = true;
$.each(data, function(key, val) {
var o = new Option(val,key);
if (first_iteration) {
o.selected = true; // ALSO TRYED $select2.html(o);
first_iteration = false;
}
$select2.append(o);
})
// Select the default value once all the options are loaded
$('.select2 option:eq(1)').prop('selected', true)
},
If there is 2 .select2 class then use index for .select2
( Check This Link for same)

Categories

Resources