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

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)

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

Dynamic populating dropdown using jquery/ajax

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"
}
]

Add ajax return value to selectbox?

I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$("#brnch_name").val(segments[17].trim());
}
});
My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?
You need to add proper html to select. Something like
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format
Here is my solution:
$("#brnch_name").empty(); //clear the drop down box
for (var i=0;i<segments.length;i++)
{
html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
$("#brnch_name").append(html);
}
You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (i, item) {
$('#branch_name').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
Use $.each like below:
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (key, value) {
$("#brnch_name").append($("<option></option>").val(segments[key].trim());
});
}
});
You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.
/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>

Change checkbox + label jquery

I got multiple checkboxes and labels and when the answer is correct I want to change the background color of the selected checkbox and label
<input type="checkbox" id="a" class="check-with-label" />
<label for="a" class="question_box">
<?php echo $vraag[0]['A'] ?>
</label>
<input type="checkbox" id="b" class="check-with-label" />
<label for="b" class="question_box">
<?php echo $vraag[0]['B'] ?>
</label>
and when the user presses submit it calls an ajax call to a script to check if it is the correct answer or not.
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
this.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
problem is I don't know how to call the correct box because when the user presses submit the this variable is now the submit button and not the checked box (There can only be one checkbox selected at the time_.
So the question is how do I replace the background color of the selected AND the correct box from
.check-with-label:checked + .question_box {
background-color: orange;
}
to
background-color:green
(and for incorrect red)
Try changing the label instead of this
You've already got the ID of the label
(var selected = $(this).attr('id');)
Which will probably return a/b/c/d and then use
$('label[for="'+selected+'"]').css('background-color', 'green'); //or red in the else statement
this styles the label for the selected id, in this case d
the code above basicly means:
$('label][for="d"].css('background-color','green'); //or red
but then using the chosen variable
Goodluck!
In success use selected_obj.css instead of this.selected and pass $(this) to selected_obj
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = $(this).attr('id');
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
//selected_box.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
Try this
$('#bottom').on('click', function(){
$('#antwoorden .check-with-label').each(function() {
var selected = $(this).attr('id');
var isChecked = $(this).is(':checked'));
if (!isChecked) {
return;
}
var selected_obj = $(this);
//var selected_box = this;
selected = selected.toUpperCase();
var data = {
vraag_nummer : <?php echo $vraag[0]['id'] ?>,
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
selected_obj.css('background-color', 'green');
} else {
selected_obj.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
After the page is rendered and displayed to user, PHP will no longer run. Therefore, in your $('#bottom').on('click' function, the PHP code won't work. The trick is to store that information when building the page, such as by writing it into a data attribute or some such.
Inside the AJAX success function the $(this) object is not available. Set it to a global variable and you will be able to access the value.
/* javascript/jQuery */
$('#bottom').on('click', function(){
$('#antwoorden input:checked').each(function() {
var selected = this.id; //faster, same result
$this = $(this);
selected = selected.toUpperCase();
var data = {
//change next line - PHP finished running
vraag_nummer : $this.attr('data-vn'),
antwoord : selected
};
console.log(data);
$.ajax({
type: 'POST',
url : 'includes/check_correct.php',
data: data,
success: function(data) {
if(data.correct){
$this.css('background-color', 'green');
} else {
$this.css('background-color', 'red');
}
},
error: function(err) {
console.log('error');
console.log(err);
}
});
});
});
<!-- HTML: -->
<input id="vraag_nummer" data-vn="<?php echo $vraag[0]['id'] ?>" type="text" />

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Categories

Resources