I'm having troubles with getting a variable from a getJSON() request. I have the following three functions:
function getPcLatitude() { // onchange
var funcid = "get_postcode_latitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLatitude) {
if (dataLatitude == null) {
//..
} else {
var myLatitude = 0;
for (var i=0;i<dataLatitude.length;i++){
myLatitude = dataLatitude[i].pc_latitude;
}
return parseFloat(myLatitude);
//alert(myLatitude);
}
});
}
function getPcLongitude() { // onchange
var funcid = "get_postcode_longitude";
var postcode = parseInt($('#input-field-postcode').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"postcode":postcode}).done(function(dataLongitude) {
if (dataLongitude == null) {
//..
} else {
var myLongitude = 0;
for (var i=0;i<dataLongitude.length;i++){
myLongitude = dataLongitude[i].pc_longitude;
}
return parseFloat(myLongitude);
//alert(myLongitude);
}
});
}
function getTop5Postcode() { // onchange
setTimeout(function() {
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var latitude = getPcLatitude();
var longitude = getPcLongitude();
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}, 0);
}
Form some reason the
var latitude = getPcLatitude();
var longitude = getPcLongitude();
parts don't work / don't get a value form the functions. When I change the return in both functions into an alert() it does give me the expected values, so those two functions work.
When I set the two variables directly, like so:
var latitude = 5215;
var longitude = 538;
then the getTop5Postcode() function does work and fills the table.
Any help on this?
Regards, Bart
Do not forget that JavaScript is asynchronous, so by the time you reach the return statement, the request is probably not done yet. You can use a promise, something like:
$.getJSON(....).then(function(value){//do what you want to do here})
Both your functions (getPcLatitude and getPcLongitude) are returning nothing because the return statement is inside a callback from an asynchronous request, and that's why an alert show the correct value.
I would suggest you to change both methods signature adding a callback parameter.
function getPcLatitude(callback) {
...
}
function getPcLongitude(callback) {
...
}
And instead of returning you should pass the value to the callback:
callback(parseFloat(myLatitude));
callback(parseFloat(myLongitude));
And your last function would be somehting like that:
function getTop5Postcode() { // onchange
setTimeout(function() {
var latitude;
var longitude;
getPcLatitude(function(lat) {
latitude = lat;
getTop5(); // Here you call the next function because you can't be sure what response will come first.
});
getPcLongitude(function(longi) {
longitude = longi;
getTop5();
});
function getTop5() {
if (!latitude || !longitude) {
return; // This function won't continue if some of the values are undefined, null, false, empty or 0. You may want to change that.
}
var funcid = "get_top_5_postcode";
var er = rangeM3Slider.noUiSlider.get();
var zv = $("#selectzv").val();
if (zv < 1) {
var zv = $("#selectzvfc").val();
}
var zp = $("#selectzp").val();
if (zp < 1) {
var zp = $("#selectzpfc").val();
}
var chosendistance = parseInt($('#input-field-afstand').val());
var jqxhr = $.getJSON('functions/getdata.php', {
"funcid":funcid,
"er":er,
"zp":zp,
"zv":zv,
"latitude":latitude,
"longitude":longitude,
"chosendistance":chosendistance}).done(function(dataPrices) {
if (dataPrices == null) {
$('#myModalAlert').modal('show');
} else {
//$('#myModalData').modal('show');
var table = '';
var iconClassZkn = '';
var iconClassIp = '';
for (var i=0;i<dataPrices.length;i++){
if (dataPrices[i].zkn_score == 0) {
iconClassZkn = 'no-score';
} else {
iconClassZkn = 'zkn-score';
}
if (dataPrices[i].ip_score == 0) {
iconClassIp = 'no-score';
} else {
iconClassIp = 'ip-score';
}
table += '<tr>'
+ '<td width="75" class="zkh-image" align="center">'+ dataPrices[i].zvln_icon +'</td>'
+ '<td width="250" align="left"><b>'+ dataPrices[i].zvln +'</b><br><i>Locatie: ' + dataPrices[i].zvln_city + '</i></td>'
+ '<td class=text-center> € '+ dataPrices[i].tarif +'</td>'
+ '<td class=text-center> € '+ dataPrices[i].risico +'</td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].zkn_url + '"><span class="' + iconClassZkn + '"><font size="2"><b>' + dataPrices[i].zkn_score + '</b></font></span></a></td>'
+ '<td class=text-center><a target="_blank" href="' + dataPrices[i].ip_url + '"><span class="' + iconClassIp + '"><font size="2"><b>' + dataPrices[i].ip_score + '</b></font></span></a></td>'
+ '</tr>';
}
$('#top5').html(table);
//$('#myModalData').modal('hide');
}
})
.fail(function() { $('#myModalAlert').modal('show');}); //When getJSON request fails
}
}, 0);
}
Of course, this is far away from the perfect solution for your problem but it should work!
And I did not test this code.
I solved this by doing some extra stuff in mysql queries. Now I only have to use the main function.
Things work now! Thanks for all the help!
Related
I am trying to achieve a dropdown box in my webpage which lists the options from the values in the database. I have achieved showing the listed options for the dropdown, but when I select the option it is not set to a value. In other words I have a doubt whether my dropdown is initialized or not.
I have added the required snippet for the action.
function add_row() {
table = document.getElementById('b_book');
var rowData = document.createElement('tr');
rowData.innerHTML = '<td>' + slno +
'</td><td id="dbSNO"><select id="SNO[' + slno + ']" onchange="detail_fetcher(this.value)" onselect="detail_fetcher(this.value)" onload="detail_fetcher(this.value)"></select></td>' +
'<td id="dbLNO"><input type="text" id="LNO[' + slno + ']" list="lot_srch_list" onkeydown="LNO_COL(event,this.value,this.id)" onfocus="lotNo_select()"/></td>' +
'<td><input type="text" id="dbMTR[' + slno + ']"/></td><td id="dbWT[' + slno + ']"></td><td id="dbMWT[' + slno + ']"></td><td id="GPM[' + slno + ']"></td><td id="dbTONE[' + slno + ']"></td><td><button id="btn_rem[' + slno + ']" onclick="remove_row()">Remove</button></td>';
table.appendChild(rowData);
slno += 1;
}
function LNO_COL(e, lno, hashtag) {
var beg_pos = hashtag.indexOf('[') + 1;
var end_pos = hashtag.indexOf(']');
var hash_pos = hashtag.substring(hashtag.lastIndexOf('[') + 1, hashtag.lastIndexOf(']'));
var postIN = 'par=' + parname.value + '&lno=' + lno;
if (e.ctrlKey) {
sNo_list = document.getElementById('SNO[' + hash_pos + ']');
sNo_list.innerHTML = '';
var XMLhLNO = new XMLHttpRequest();
XMLhLNO.onreadystatechange = function () {
if ((this.readyState === 4) && (this.status === 200)) {
var result = this.responseText;
var JSON_result = JSON.parse(result);
for (z in JSON_result) {
var sno_opt;
sno_opt = document.createElement('option');
sno_opt.value = JSON_result[z].slno;
sno_opt.text = JSON_result[z].slno;
sNo_list.appendChild(sno_opt);
}
}
};
XMLhLNO.open('POST', 'sno_lot_par2.php', true);
XMLhLNO.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
XMLhLNO.send(postIN);
detail_fetcher(hashtag);
}
}
function detail_fetcher(hash_position) {
var row_no = hash_position.substring(hash_position.lastIndexOf('[') + 1, hash_position.lastIndexOf(']'));
var serial_row = document.getElementById('SNO[' + row_no + ']');
alert(serial_row.);
/* var XMLfetcher = new XMLHttpRequest();
XMLfetcher.onreadystatechange = function()
{
if((this.readyState == 4)&&(this.status == 200))
{
var src_result = this.responseText;
var JSON_res = JSON.parse(src_result);
alert(serial_row_db);
alert(src_result);
}
};
XMLfetcher.open('POST','srch_lot2.php',true);
XMLfetcher.setRequestHeader('Content-type','application/x-www-form-urlencoded');
XMLfetcher.send(('row=' + serial_row_db));
*/
}
I have tried using value method, selecteditem(index) method but none of them proves to be successful.
Note: I want to use pure JavaScript as I am quite confused with using jQuery.
I'm running a site using Node, Express and MongoDB. I generate containers after an ajax call to get the data to fill them with, and each of the containers has a button which makes another ajax call specific to a recipe it's getting detailed information on. The first Time I do this it works perfectly, but if i get details for a 2nd one it executes the function 3 times instead of one, and if I do it for a 3rd container it runs it 9 times and so on. I'm fairly new with Jquery and perhaps It's a misunderstanding of how the events work. the problems also occurs with the saveRecipe function.
global.js
$(document).ajaxComplete(function(){
$('.details').popover({"trigger": "manual", "html":"true"});
$('.details').click(get_data_for_popover_and_display);
$('.save-favorite').on('click', saveRecipe );
});
(function ($) {
$('#search').on('click', function (e) {
// remove resultset if this has already been run
$('.recipes').empty();
var recipeName = document.getElementById('recipeName').value;
var recipeNameString = '&q=' + recipeName;
var ingredientHtml = '&allowedIngredient[]=';
var ingredientsArray = document.getElementById('ingredients').value.split(",");
var ingredientsString = '';
if (ingredientsArray[0] !== ""){
for (i = 0; i < ingredientsArray.length; i++){
ingredientsArray[i] = ingredientHtml + ingredientsArray[i].trim();
}
for (i = 0; i < ingredientsArray.length; i++){
ingredientsString += ingredientsArray[i];
}
}
var excludedIngredientHtml = '&excludedIngredient[]=';
var excludedIngredientsArray = document.getElementById('ingredientsExclude').value.split(",");
var excludedIngredientsString = '';
if (excludedIngredientsArray[0] !== ""){
for (i = 0; i < excludedIngredientsArray.length; i++){
excludedIngredientsArray[i] = excludedIngredientHtml + excludedIngredientsArray[i].trim();
}
for (i = 0; i < excludedIngredientsArray.length; i++){
excludedIngredientsString += excludedIngredientsArray[i];
}
}
var dietHtml = '';
if(document.getElementById('lacto-veg').checked){
dietHtml += '&allowedDiet[]=388^Lacto vegetarian';
}
if(document.getElementById('ovo-veg').checked){
dietHtml += '&allowedDiet[]=389^Ovo vegetarian';
}
if(document.getElementById('paleo').checked){
dietHtml += '&allowedDiet[]=403^Paleo';
}
if(document.getElementById('pescetarian').checked){
dietHtml += '&allowedDiet[]=390^Pescetarian';
}
if(document.getElementById('vegan').checked){
dietHtml += '&allowedDiet[]=386^vegan';
}
if(document.getElementById('vegetarian').checked){
dietHtml += '&allowedDiet[]=387^Lacto-ovo vegetarian';
}
var allergyHtml = '';
if(document.getElementById('dairy-free').checked){
allergyHtml += '&allowedAllergy[]=396^Dairy-Free';
}
if(document.getElementById('egg-free').checked){
allergyHtml += '&allowedAllergy[]=397^Egg-Free';
}
if(document.getElementById('gluten-free').checked){
allergyHtml += '&allowedAllergy[]=393^gluten-Free';
}
if(document.getElementById('peanut-free').checked){
allergyHtml += '&allowedAllergy[]=394^Peanut-Free';
}
if(document.getElementById('seafood-free').checked){
allergyHtml += '&allowedAllergy[]=398^Seafood-Free';
}
if(document.getElementById('seseme-free').checked){
allergyHtml += '&allowedAllergy[]=399^Seseme-Free';
}
if(document.getElementById('sulfite-free').checked){
allergyHtml += '&allowedAllergy[]=401^Sulfite-Free';
}
if(document.getElementById('tree-nut-free').checked){
allergyHtml += '&allowedAllergy[]=395^Tree Nut-Free';
}
if(document.getElementById('wheat-free').checked){
allergyHtml += '&allowedAllergy[]=392^Wheat-Free';
}
var apiHtml = 'http://api.yummly.com/v1/api/recipes?_app_id=&_app_key=' +recipeNameString;
if (ingredientsString){
apiHtml += ingredientsString;
}
if (excludedIngredientsString){
apiHtml += excludedIngredientsString;
}
if (dietHtml){
apiHtml += dietHtml;
}
if (allergyHtml){
apiHtml += allergyHtml;
}
apiHtml += '&requirePictures=true';
apiHtml = apiHtml.replace(' ', '%20');
$.getJSON(apiHtml, function (json) {
var recipes = [],
$recipes;
$.each(json, function (key, val) {
if (key === "matches"){
for (i = 0; i < val.length ; i++) {
if (i%3 === 0){
recipes.push('<div class="row">');
}
recipes.push('<div class="col-sm-6 col-md-4">');
recipes.push('<div class="thumbnail">' + '<img src="'+ val[i].imageUrlsBySize[90] + '" alt="' + val[i].recipeName + '" data-holder-rendered="true" style="height: 300px; width: 100%; display: block;"/>');
recipes.push('<div class="caption">' + '<h3 class="caption-text">' + val[i].recipeName + '</h3>');
recipes.push('<p class="caption-text">' + val[i].sourceDisplayName + '</p>');
recipes.push('<p><button type="button" class="btn btn-primary details" data-toggle="popover" title="' + val[i].recipeName + '" value="' + val[i].id + '"> Details </button> ');
recipes.push('<button type="button" class="btn btn-primary save-favorite" method="post" action="saveFavorite" value="' + val[i].id + '"> Favorite </button></p>');
recipes.push('</div></div></div>');
if ((i+1)%3 === 0){
recipes.push('</div>');
}
}
}
});
if (recipes.length < 1) {
recipes.push('<p>No results for parameters, try again!</p>');
}
$recipes = $('<div />').appendTo('.recipes');
$recipes.append(recipes.join(''));
});
e.preventDefault();
});
}(jQuery));
get_data_for_popover_and_display = function() {
var el = $(this);
if(el.hasClass('recipe-loaded')){
}
else {
var _data = $(this).attr('alt');
var recipeUrl = 'http://api.yummly.com/v1/api/recipe/' + this.value + '?_app_id=&_app_key=';
var recipeHtml = '';
var ingredientsHtml = '';
var nutritionHtml = '';
var ratingHtml = '';
var servingsHtml = '';
var sourceHtml = '';
$.getJSON(recipeUrl, function (json) {
$.each(json, function (key, val) {
if (key === "ingredientLines"){
ingredientsHtml = '<h4>Ingredients:</h4><ul>';
for (i = 0; i < val.length ; i++){
ingredientsHtml += ('<li>' + val[i] + '</li>');
}
ingredientsHtml += '</ul>';
}
if (key === "nutritionEstimates"){
if(val.length > 0){
nutritionHtml = 'Cal. per Serving: ' + val[0].value + '<br>';
}
}
if (key === "rating"){
ratingHtml += 'Rating: ' + val + '</p>';
}
if (key === "numberOfServings"){
servingsHtml += '<p>Servings: ' + val + '<br>';
}
if (key === "source"){
sourceHtml += '<p><a type="button" class="btn btn-primary details" href="'+ val.sourceRecipeUrl +'" >Source</a>';
}
})
recipeHtml += ingredientsHtml;
recipeHtml += servingsHtml;
recipeHtml += nutritionHtml;
recipeHtml += ratingHtml;
recipeHtml += sourceHtml;
el.attr('data-content', recipeHtml).success(el.popover('toggle'));
el.addClass('recipe-loaded');
});
}
};
function saveRecipe(){
var recipeUrl = 'http://api.yummly.com/v1/api/recipe/' + this.value + '?_app_id=3e5b7dbe&_app_key=1d681685a57dac07e6df0b1c0df38de6';
var json = $.getJSON(recipeUrl, function (data){
console.log(JSON.stringify(data));
$.ajax({
type: 'POST',
data: data,
url: '/saverecipe',
dataType: 'JSON'
});
});
};
This line:
$('.details').click(get_data_for_popover_and_display);
hooks up a new event handler on all .detail elements that will call get_data_for_popover_and_display, even if that element already has an event handler calling get_data_for_popover_and_display. Same with:
$('.save-favorite').on('click', saveRecipe );
So since get_data_for_popover_and_display (at least) does another ajax call, which will add another handler, you'll get increasing numbers of handlers over time.
It's exactly like this:
function clickHandler() {
console.log(+new Date(), "Clicked");
clickComplete();
}
function clickComplete() {
$("#btn").on("click", clickHandler);
}
clickComplete();
<input type="button" id="btn" value="Click Me">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So: Only add a handler if you haven't already done so. Perhaps keep track in jQuery's data store:
function clickHandler() {
console.log(+new Date(), "Clicked");
clickComplete();
}
function clickComplete() {
$("#btn").filter(function() {
return !$(this).data("hasClick");
})
.on("click", clickHandler)
.data("hasClick", true);
}
clickComplete();
<input type="button" id="btn" value="Click Me">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Is there a reason why my Ajax call will not work inside of an if statement? I may be doing something fundamentally wrong here because I don't have a lot of experience with JS or Ajax. Thanks
The working js function is:
function filter(varType, varValue) {
var $products = $('#products');
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></div>';
$products.append(elt2);
}
}
});
}
But if I were to do this, it suddenly stops working:
function filter(varType, varValue) {
var $products = $('#products');
var x = 5
var y = 6
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
}
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></div>';
$products.append(elt2);
}
}
});
}
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></div>';
$products.append(elt2);
}
}
});
}
This is valid syntax. You need to move the .success inside the parenthesis.
You closed the curly brace of your if- statement too soon:
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
//} <-- TOO EARLY
.success(function (data) {
....
});
} <-- SHOULD BE HERE INSTEAD
End the if statement after the .success() callback.
I have been following an online tutorial to autocomplete textboxes with database values after the user enters a code greater than 7 characters. I have completed most of what I am trying to achieve however I cannot seem to select a value from the combobox to autocomplete the textbox.
I dont have much javascript experience but I am hoping the problem is something small in what I already have, can someone please recommend the change I need to make to select the value from the combobox.
public ActionResult MultiColumnComboBox(string SearchFor, string ControlId)
{
ViewBag.ProcId = SearchFor.Trim();
ViewBag.ControlBlockId = "block" + ControlId.Trim();
ViewBag.ControlId = ControlId.Trim();
ViewBag.ControlTxtId = "txt" + ControlId.Trim();
return View();
}
public JsonResult LoadComboData(string strSearch, string SearchFor)
{
efacsdbEntities db = new efacsdbEntities();
strSearch = strSearch.Trim();
if (SearchFor.Trim() == "employee" && strSearch.Length>7)
{
var res = (from E in db.allpartmasters
where E.partnum.ToLower().Contains(strSearch.ToLower()) || E.partdesc.ToLower().Contains(strSearch.ToLower())
select new
{
E.partnum,
E.partdesc
}).ToList();
return Json(res, JsonRequestBehavior.AllowGet);
}
return Json(null, JsonRequestBehavior.AllowGet);
}
<input type="hidden" id="#ViewBag.ProcId" name="#ViewBag.ProcId" value="" />
<input type="hidden" id="#ViewBag.ControlId" name="#ViewBag.ControlId" value="" />
<input type="text" name="#ViewBag.ControlTxtId" id="#ViewBag.ControlTxtId" autocomplete="on" />
<div class="#ViewBag.ControlTxtId renderpart">
<div class="DataBlock">
<div id="#ViewBag.ControlBlockId" style="max-width: 520px;">
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../Scripts/json.debug.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".renderpart").hide();
var txtid = "#" + '#ViewBag.ControlTxtId';
var renderpart = "." + '#ViewBag.ControlTxtId';
var selectlinkvalueid = ".Get" + '#ViewBag.ProcId';
$(selectlinkvalueid).on("click", function () {
var value = $(this).attr('id');
var valueText = $(this).attr('title');
$("##ViewBag.ControlId").val(value);
$(txtid).val(valueText);
$(renderpart).slideUp("slow");
});
$(txtid).keyup(function () {
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var activecols = $("#hdnActiveColumns").val();
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
$(txtid).focusin(function () {
var txtid = "#" + '#ViewBag.ControlTxtId';
var value = $(txtid).val();
var Procvalue = '#ViewBag.ProcId';
var controlid = "#" + '#ViewBag.ControlBlockId';
value = encodeURI(value);
if (value.length > 2) {
$.ajaxSetup({ cache: false });
$.getJSON("/Test/LoadComboData", { strSearch: " " + value, SearchFor: " " + Procvalue }, function (data) {
$(controlid).html("");
var htmlrow = "";
var tempprocId = '#ViewBag.ProcId';
var jsondata = JSON.stringify(data);
$(controlid).html(CreateDynamicTable(jsondata, tempprocId));
$(renderpart).slideDown("slow");
});
$.ajaxSetup({ cache: true });
}
else {
$(renderpart).slideUp("slow");
}
});
function CreateDynamicTable(objArray, tempprocId) {
var array = JSON.parse(objArray);
var str = '<table style="width:100%;">';
str += '<tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr>';
str += '<tbody>';
var flag = false;
var ids;
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr>' : '<tr>';
for (var index in array[i]) {
if (flag == false) {
ids = array[i][index];
flag = true;
}
str += '<td><a id="' + ids + '" class="Get' + tempprocId + '" title="' + array[i][index] + '" href="#">' + array[i][index] + '</a></td>';
}
str += '</tr>';
}
str += '</tbody>';
str += '</table>';
return str;
}
});
$(document).click(function (evt) {
var renderpart = "." + '#ViewBag.ControlTxtId';
var theElem = (evt.srcElement) ? evt.srcElement : evt.target;
if (theElem.id == "main" || theElem.id == "sub1") {
$(renderpart).slideUp("fast");
}
});
</script>
Here is the link to the tutorial I was following as well.
Create Multiple column autocomplete combobox
HTML:-
In the body tag I have used onload="variable2.init() ; variable1.init();".
JavaScript:-
var variable1 = {
rssUrl: 'http://feeds.feedburner.com/football-italia/pAjS',
init: function() {
this.getRSS();
},
getRSS: function() {
jQuery.getFeed({
url: variable1.rssUrl,
success: function showFeed(feed) {
variable1.parseRSS(feed);
}
});
},
parseRSS: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable1.parsefootballitaliaRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content1" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens1\', \'#blog_posts1\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts1\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen1').html(main);
jQuery('#blog_posts1').html(posts);
},
parsefootballitaliaRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
var variable2 = {
weatherRSS: 'http://feeds.feedburner.com/go/ELkW',
init: function() {
this.getWeatherRSS();
},
getWeatherRSS: function() {
jQuery.getFeed({
url: variable2.weatherRSS,
success: function showFeed(feed) {
variable2.parseWeather(feed);
}
});
},
parseWeather: function(feed) {
var main = '';
var posts = '';
var className = 'even';
var pst = {};
for (i = 0; i < feed.items.length; i++) {
pst = variable2.parsegoRSS(feed.items[i]);
if (className == 'odd') {
className = 'even';
}
else {
className = 'odd';
}
var shorter = pst.story.replace(/<(?:.|\n)*?>/gm, '');
item_date = new Date(feed.items[i].updated);
main += '<div id="content2" class="post-main ' + className + '" onclick="mwl.setGroupTarget(\'#screens2\', \'#blog_posts2\', \'ui-show\', \'ui-hide\');mwl.setGroupTarget(\'#blog_posts2\', \'#post' + (i+1) + '\', \'ui-show\', \'ui-hide\');">';
main += '<b>' + pst.title.trunc(55, true) + '</b><br />' + shorter.trunc(30, true);
main += '<div class="datetime">' + item_date.getDateTime() + '</div></div>';
posts += '<div class="post-wrapper ui-hide" id="post' + (i+1) + '">';
posts += '<div class="post-title"><b>' + pst.title + '</b></div>';
posts += feed.items[i].description;
posts += '</div>';
}
jQuery('#main_screen2').html(main);
jQuery('#blog_posts2').html(posts);
},
parsegoRSS: function(item) {
var match = item.description.match('src="([^"]+)"');
var part = item.description.split('<font size="-1">');
var arr = {
title: item.title,
link: item.link,
image: match,
site_title: item.title,
story: item.description
};
return arr;
}
};
When I run the program it only reads one of the variables i.e. either 1 or 2.
How can I correct them to read both the variables?
Use this.
<script type="text/javascript">
window.onload = function() {
variable1.init();
variable2.init();
}
</script>
Try this
<body onload="callFunctions()">
JS-
function callFunctions()
{
variable1.init();
variable2.init();
}
Update-
Also
there are other different ways to call multiple functions on page load
Hope it hepls you.