How to retrieve value from a div dynamically? - javascript

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)

Related

When using bootstrap-multiselect and 'Select All' is selected, it is not triggering the AJAX call

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?

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

Select option does not show data

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 :)

Jquery each data object attribute

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.

how to clean option values under select - html tag

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

Categories