This is my first attempt to databind an html control via ajax. I check/debug my ajax call and the data are retrieved OK, but the do not appear in the select option. My javascript is located at the bottom of my aspx page. What's the problem
$(function () {
$.ajax({
type: "POST",
url: "psHlp.asmx/getDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#District").empty();
$.each(msg.d, function () {
$("#District").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load districts");
}
});
});
This is my select option which is located at the beginning of my page
<div class="col-sm-3 col-xs-12 ffield">
<select id="District" style="display: none;">
</select>
</div>
Try using like this on your each loop.
var options;
$.each(msg.d, function () {
options += '<option value="' + this["Value"] + '">' + this["Text"] + '</option>';
});
console.log(options);
$("#District").append(options);
You need to specify (index,value) params in your $.each callback function and use value to access the iterated elements. Something like this.
$.each(msg.d, function (index,value) {
$("#District").append("<option value='" + value.Value + "'>" + value.Text + "</option>");
});
Finally I found the solution. All the above suggestions were correct. The problem occurred because I'm using bootstarp js/css (customer's designer provided the layout), so I need to rebuild the multiselect option after the append.
var options = "";
$.each(response.d, function () {
options += '<option value="' + this['Value'] + '">' + this['Text'] + '</option>';
});
$("#Town").append().html(options);
$("#Town").multiselect('rebuild');
Hope this will help at least one person :)
Related
I have a problem with jquery append. This is the code:
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
This code work very well, but not every time. (only the append option not working. This: console.log(string_option) it`s ok every time).
Can you help me, please?
Thank you!!
Looks like you need to put the code to be executed after the document is fully loaded using the "$( document ).ready" jQuery event
$( document ).ready(function() {
$.ajax({
method: "POST",
url:
"/getcars.php",
data: {
model_car: sessionStorage.getItem("model")
}
}).done(function(msg) {
var obj = JSON.parse(msg);
$("#model").empty().append('<option value="-1">Model</option>');
var string_option = "";
Object.keys(obj.model).forEach(function(key) {
string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
});
console.log(string_option);
$("#model").append(string_option);
})
});
You can learn more about this on the below link
https://api.jquery.com/ready/
Try to check the response on Ajax success sometimes it happens due to malformed JSON is sent back with a 200/OK
One possible problem could be that you run the .append() before DOM is loaded. If this is the problem you can try 2 methods:
put this javascript code inside footer.
add to your code:
$(document).ready(function(){
//... your ajax request
})
I have two dropdown lists which one of them is dependent on the other. Let's call is multiselect 1 and multiselect 2. Based on the value selected in multiselect1, multiselect 2's dropdown list changes via ajax call.
I am triggering my ajax call based on 'onChange'.
However, when user opens the page and as default all values will be selected in multiselect 1 but as my current set-up is only for onchange, how to trigger my ajax call based on all selected as default?
On change AJAX Call which perfectly works except when all selected --->
$('#market-select').multiselect(
{
includeSelectAllOption: true,
selectAllValue: 'multiselect-all',
filterBehavior: 'value',
enableFiltering: true,
buttonWidth: '270px',
onChange: function (option, checked) {
var markets = $('#market-select option:selected');
var selected = [];
var json = "'" + JSON.stringify(selected) + "'";
$(markets).each(function (index, markets) {
selected.push($(this).val())
});
$.ajax({
type: "POST",
dataType: "json",
url: _config.GetCampaignsByMarket,
data: JSON.stringify({
marketValue: selected
}),
contentType: 'application/json',
success: function (data) {
var items = ''; //the original example which makes constant call to dom when the other one makes call only twice
$('.select-ajax').empty();
$.each(data, function (key, val) {
$('.select-ajax').append('<option selected value="' + val.CampaignInitiative + '">' + val.CampaignInitiative + '</option>');
items += "<option value='" + val.CampaignInitiative + "'>" + val.CampaignInitiative + "</option>";
});
$('.select-ajax').multiselect('rebuild');
},
error: function (xhr, status, error) {
}
});
}
});
Attemt to initialize ajax call on initialization which clearly does not work. I am going crazy at this point.
$("#market-select").multiselect('selectAll', false);
$("#market-select").multiselect('updateButtonText');
var allMarkets = $('#market-select:selected').map(function (a, item) {
$.ajax({
type: "POST",
dataType: "json",
url: _config.GetCampaignsByMarket,
data: JSON.stringify({
marketValue: allMarkets
}),
contentType: 'application/json',
success: function (data) {
var items = ''; //the original example which makes constant call to dom when the other one makes call only twice
$('.select-ajax').empty();
$.each(data, function (key, val) {
$('.select-ajax').append('<option selected value="' + val.CampaignInitiative + '">' + val.CampaignInitiative + '</option>');
items += "<option value='" + val.CampaignInitiative + "'>" + val.CampaignInitiative + "</option>";
});
//var options = data.map(function (o) {
// return '<option selected value="' + o.CampaignInitiative + '">' + o.CampaignInitiative + '</option>'; // faster as it only accesses the DOM twice, compared to the original's 2+N array items.'
//}).join('');
$('.select-ajax').multiselect('rebuild');
},
error: function (xhr, status, error) {
}
});
});
Right here bootstrap-multiselect has onSelectAll configuration. Is that what you're looking for?
I am trying to create table rows containing data from each attribute from my object response using $.each, however the Id, Purpose, and Amount are coming back undefined. I have tested the response in Fiddler and the data is all being received correctly, the problem just seems to be in the "item" part. Here is my Jquery:
$.ajax({
type: "GET",
url: "https://chad-test4.clas.uconn.edu/api/Commitments/GetCommitmentPurposes/2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var purposes = $("#purposes tbody");
if (response.Success == true) {
purposes.empty();
var buttons = '<tr><td><button type="button" class="btn-primary">Save</button>'
+ '<button type="button" class=".btn-danger">Delete</button></td>'
var list = response.Data;
$.each(list, function (i, item) {
purposes.append(buttons + '<td><select id=' + item.Id + '>' + item.Purpose + '</select>'
+ '<td><input type="text" val =' + item.Amount + '/>')
});
}
}
});
});
Could you post a snippet of JSON aswell ?
Basically I believe what you need to do is to access the entries by an identifier:
$.each( list.items, function(i, item ) {
But posting JSON would clarify if that is true.
I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});
Guys I have a function which uses ajax call to retrieve data dynamically based upon a value in div. Now lastNoticeID value in the function is not getting updated as its not in any loop..thus it keeps repeating the same data..
CODE :
function callMoreData() {
var lastNoticeID = $('#hiddenLastNoticeID').val();
$.ajax({
type: "GET",
url: "/api/values/getnotice?num=" + lastNoticeID,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
$.each(data, function (index, value) {
BindNotice(value);
});
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input id="hiddenLastNoticeID" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
As you can see in the code above, I am retrieving value from the above div and then passing it to webApi url... Now this is running fine and on the first scroll I get the values but then the function keeps repeating the same values over and over again i.e. var lastNoticeID is not getting updated. How do I get it to update per scroll event?
btw divNotices has the same html code as BindNotice function.
Use classes instead:
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
}
And then:
var lastNoticeID = $('.hiddenNotice').last().val();
Or, you could just store the LastNoticeID in a variable:
var lastNoticeID = 0;
function BindNotice(values) {
$('#divNotices').append('...some code...' +
'<input class="hiddenNotice" type="hidden" value="' + values.LastNoticeID +
'" />' + '...some code...');
lastNoticeID = values.LastNoticeID;
}
It would seem that you are adding more elements of the same ID. ID's are supposed to be single instance and Jquery will therefore only grab the first instance in the DOM. (Which is why $('#hiddenLastNoticeID').val(); is the same every time)