jQuery mobile mega dropdown adds more and more buttons - javascript

I am using a jquery plugin to generate a mega dropdown on my mobile website:
The menu is generated dynamically: everytime the user clicks on the right arrow, an api call is made to gather all sub-points to the clicked menu-entry. Down the menu everything works fine, but when I click on "back" it seems that there is added a forward/back-button for each menu-level:
This is my code:
// Catching the click-event
$(document).on('click','.next-button', function(){
var subCatContainer = $(this).next('.subcats');
var current = $(this).parent('.shopCatWithSub');
var categoryid = current.data('categoryuuid');
console.log('Next clicked');
console.log(categoryid);
if(typeof categoryid !== "undefined"){
buildSubcats(categoryid, subCatContainer, standardUrl);
} else {
console.log("No category set!");
}
});
// Get subcategories from API:
function buildSubcats(catid, subCatContainer, standardUrl) {
$.ajax({
type: 'GET',
url: 'https://my-awesome-url.de/api?category-id=' + catid,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
handleResponse(data, subCatContainer, standardUrl);
},
error: function(XMLHttpRequest, textStatus, errorThrow) {
console.log(errorThrow);
if (jQuery.isFunction(callback)) {
}
}
});
}
// Build and add new nav-elements:
function handleResponse(data, subCatContainer, standardUrl){
var output = '';
$.each(data, function(key, category){
var element = '';
var uladd = "";
var aClassAdd = "";
if(category.hasSubcategories) {
uladd = '<ul class="subcats"></ul>';
aClassAdd = 'has-next-button';
}
element = '<li class="shopCatWithSub" data-categoryuuid="' + category.categoryUUID + '">'
+ '<a class="text-truncate menu-item ' + aClassAdd + '" href="' + standardUrl + category.categoryUUID + '">'
+ '<i class="icon-' + category.categoryIconClass + ' mr-2"></i>'
+ category.displayName
+ '</a>'
+ uladd
+ '</li>';
output += element;
});
subCatContainer.empty();
subCatContainer.html(output);
// Re-initialize menu
$('.nav-mobile').mobileMegaMenu();
}
I assume that there is a problem with the re-initializing of the complete menu-structure. But I can't figure out how to handle it.

Related

Display data received from drop box value

I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);

Functions are not working in Ajax after a while

I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}

I have javascript code to view a news from RSS as a vertical list. I need help to move the list of topics as horizontal one by one, in one line

I have javascript code to view a news from RSS as a vertical list.
(function ($) {
$.fn.FeedEk = function (opt) {
var def = $.extend({
MaxCount: 5,
ShowDesc: true,
ShowPubDate: true,
DescCharacterLimit: 0,
TitleLinkTarget: "_blank",
DateFormat: "",
DateFormatLang:"en"
}, opt);
var id = $(this).attr("id"), i, s = "", dt;
$("#" + id).empty();
if (def.FeedUrl == undefined) return;
$("#" + id).append('<img src="loader.gif" />');
var YQLstr = 'SELECT channel.item FROM feednormalizer WHERE output="rss_2.0" AND url ="' + def.FeedUrl + '" LIMIT ' + def.MaxCount;
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=" + encodeURIComponent(YQLstr) + "&format=json&diagnostics=false&callback=?",
dataType: "json",
success: function (data) {
$("#" + id).empty();
if (!(data.query.results.rss instanceof Array)) {
data.query.results.rss = [data.query.results.rss];
}
$.each(data.query.results.rss, function (e, itm) {
s += '<li><div class="itemTitle"><a href="' + itm.channel.item.link + '" target="' + def.TitleLinkTarget + '" >' + itm.channel.item.title + '</a></div>';
if (def.ShowPubDate){
dt = new Date(itm.channel.item.pubDate);
s += '<div class="itemDate">';
if ($.trim(def.DateFormat).length > 0) {
try {
moment.lang(def.DateFormatLang);
s += moment(dt).format(def.DateFormat);
}
catch (e){s += dt.toLocaleDateString();}
}
else {
s += dt.toLocaleDateString();
}
s += '</div>';
}
if (def.ShowDesc) {
s += '<div class="itemContent">';
if (def.DescCharacterLimit > 0 && itm.channel.item.description.length > def.DescCharacterLimit) {
s += itm.channel.item.description.substring(0, def.DescCharacterLimit) + '...';
}
else {
s += itm.channel.item.description;
}
s += '</div>';
}
});
$("#" + id).append('<ul class="feedEkList">' + s + '</ul>');
}
});
};
})(jQuery);
I need help to move the list of topics as horizontal one by one, in one line. by used javascript code. this code display just 5 topics, which I need it, but I have problem to how can I movement it as horizontal.

Retrieveing Multiple lines of text using var query

I currently have a JS file which displays a single line know issue entered by a user via a SharePoint list. The div id it displays on the page is 'knowntitle'.
I now have been asked to display further information, so that the user would have another field to fill in on the SharePoint list called Further Details would be a Multiple Lines of Text field.
I wrote the original pages a year ago, and I'm a bit rusty! I've made a start and commented out what I've done so far. Any help on how to proceed would be gratefully received, js below:
function getDeviceKnownIssues() {
//var txtfurtherinfo = "";
var txtTitleKnown = "<ol>";
var query = "http://xxx/sites/it/ITInfrastructure/_vti_bin/listdata.svc//Knownissues?$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
$.each(data.d.results, function(index, item) {
var KnownTitle = item.Title;
//var FurtherInfo = item.Info;
txtTitleKnown = txtTitleKnown + "<li>" + KnownTitle + "</li>";
});
txtTitleKnown = txtTitleKnown + "</ol>";
//$('furtherinfo').append(txtName);
$('#knowntitle').append(txtTitleKnown);
});
call.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error retrieving data: " + jqXHR.responseText);
});
}
You can concatenate the further info together with line breaks \r\n and them display them in the cell:
$.each(data.d.results, function(index, item) {
txtTitleKnown += "<li>" + item.Title + "</li>";
if(item.Info != undefined) {
txtfurtherinfo += item.Info + "\r\n";
}
});
txtTitleKnown = txtTitleKnown + "</ol>";
$('#knowntitle').append(txtTitleKnown);
$('#furtherinfo').append(txtfurtherinfo);

JQuery Ajax button isn't working

I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>

Categories