multiple onload error in HTML - javascript

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.

Related

Functions being exponentially repeated in my js file

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>

problems with storing getjson request in variable

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!

Autocompleting textbox from jquery combobox

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

How to get text from textarea including the newline characters?

In jquery, I am trying to get the text from a textarea tag, with the new lines as \n and not br tags. The problem is if I select it and get its val, the firefox debugger does not even show the \n or br. If I alert it, then I see there is two lines, but then if I insert it into the DOM, it removes all the new lines. I want it to keep its new lines.
I get it like this:
var handleSend = function(thread_id) {
var user = GLOBAL_DATA.user;
$(context).find("#message-form").unbind('submit').submit(function() {
var field = $(this).find("textarea");
runAJAXSerial($(this).serialize(), {
page : 'message/setmessage',
id : user['id'],
thread_id : thread_id
}, function(response) {
var user = GLOBAL_DATA.user;
var obj = {
user_id : user['id'],
message : field[0].value.replace(/<br\s*\/?>/mg,"\n"),
date_sent : getDate() + ' ' + getTime()
};
alert(obj.message);
cleanResponse(obj);
field.val("").focus();
displayMessages([obj], true);
}, function(data,status,xhr) {
});
return false;
});
};
function cleanResponse(response) {
if (Object.prototype.toString.call( response ) === '[object Array]') {
var i = 0, l = response.length;
for (i=0; i<l; i+=1) {
response[i] = cleanResponse(response[i]);
}
} else if (Object.prototype.toString.call( response ) === '[object Object]') {
for (var property in response) {
if (response.hasOwnProperty(property)) {
response[property] = cleanResponse(response[property]);
}
}
} else {
response = escapeHTML(response);
}
return response;
}
function escapeHTML(str) {
return $("<p/>").text(str).html();
}
var displayMessages = function(response, onBottom) {
var user = GLOBAL_DATA.user, i=0, l=response.length, acc = '';
for(i=0; i<l; i+=1) {
var obj = response[i];
var acc_temp = "";
acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
acc_temp += '<img src="' + getImage(obj['user_id']) + '" align="right" class="message-image" />';
acc_temp += '<div>' + Autolinker.link(obj['message']) + '</div>';
acc_temp += '<br/>';
if (obj['user_id']!=user['id']) {
acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
}
acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
acc_temp += '</div>';
acc = acc_temp + acc;
}
addMessage(acc, onBottom);
};
var addMessage = function(html, onBottom) {
var list = $(context).find("#message-list");
if (onBottom) {
list.append(html);
scrollBot();
} else {
list.prepend(html);
}
};
displayMessages inserts the text into the DOM.
cleanResponse encodes the text so that the user can't execute scripts.
Does anyone know whats wrong?
Thanks
New lines in the DOM are treated like any other whitespace. You are getting the expected behaviour of adding the new lines.
If you want an new line to be rendered then you need to use a <br> element or modify the white-space CSS property.

How can I open with blank page on this rss javascript nor html?

I have a website which includes this RSS JavaScript. When I click feed, it opens same page, but I don't want to do that. How can I open with blank page? I have my current HTML and JavaScript below.
HTML CODE
<tr>
<td style="background-color: #808285" class="style23" >
<script type="text/javascript">
$(document).ready(function () {
$('#ticker1').rssfeed('http://www.demircelik.com.tr/map.asp').ajaxStop(function () {
$('#ticker1 div.rssBody').vTicker({ showItems: 3 });
});
});
</script>
<div id="ticker1" >
<br />
</div>
</td>
</tr>
JAVASCRIPT CODE
(function ($) {
var current = null;
$.fn.rssfeed = function (url, options) {
// Set pluign defaults
var defaults = {
limit: 10,
header: true,
titletag: 'h4',
date: true,
content: true,
snippet: true,
showerror: true,
errormsg: '',
key: null
};
var options = $.extend(defaults, options);
// Functions
return this.each(function (i, e) {
var $e = $(e);
// Add feed class to user div
if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');
// Check for valid url
if (url == null) return false;
// Create Google Feed API address
var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
if (options.limit != null) api += "&num=" + options.limit;
if (options.key != null) api += "&key=" + options.key;
// Send request
$.getJSON(api, function (data) {
// Check for error
if (data.responseStatus == 200) {
// Process the feeds
_callback(e, data.responseData.feed, options);
}
else {
// Handle error if required
if (options.showerror) if (options.errormsg != '') {
var msg = options.errormsg;
}
else {
var msg = data.responseDetails;
};
$(e).html('<div class="rssError"><p>' + msg + '</p></div>');
};
});
});
};
// Callback function to create HTML result
var _callback = function (e, feeds, options) {
if (!feeds) {
return false;
}
var html = '';
var row = 'odd';
// Add header if required
if (options.header) html += '<div class="rssHeader">' + '' + feeds.title + '' + '</div>';
// Add body
html += '<div class="rssBody">' + '<ul>';
// Add feeds
for (var i = 0; i < feeds.entries.length; i++) {
// Get individual feed
var entry = feeds.entries[i];
// Format published date
var entryDate = new Date(entry.publishedDate);
var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();
// Add feed row
html += '<li class="rssRow ' + row + '">' + '<' + options.titletag + '>' + entry.title + '</' + options.titletag + '>'
if (options.date) html += '<div>' + pubDate + '</div>'
if (options.content) {
// Use feed snippet if available and optioned
if (options.snippet && entry.contentSnippet != '') {
var content = entry.contentSnippet;
}
else {
var content = entry.content;
}
html += '<p>' + content + '</p>'
}
html += '</li>';
// Alternate row classes
if (row == 'odd') {
row = 'even';
}
else {
row = 'odd';
}
}
html += '</ul>' + '</div>'
$(e).html(html);
};
})(jQuery);
try change this:
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'
to
html += '<li class="rssRow '+row+'">' +
'<'+ options.titletag +'>'+ entry.title +'</'+ options.titletag +'>'

Categories

Resources