dynamically add list item to ul using jquery - javascript

I have the following html structure:
<div id="gw-sidebar" class="gw-sidebar">
<div class="nano-content">
<ul class="gw-nav gw-nav-list">
<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>
//===>Need to add the new list using Jquery here
</ul>
</div>
</div>
I want to add a list as shown below using jquery to the class 'init-un-active' shown above:
<li class="init-arrow-down"> <span class="gw-menu-text">Scenario-1</span> <b class="gw-arrow"></b>
<ul class="gw-submenu">
<li> Scenario </li>
<li> Resolutions </li>
<li> Triggers </li>
</ul>
</li>
How do i use jquery to add this code dynamically to the aforementioned class?
I have tried the following but it wont work:
<script type="text/javascript">
function loadScenarioForm () {
SideMenu.createBaseEntry();
// ScenarioForm.create();
}
var SideMenu = {
container : null,
scenarioCount : 0,
scenarioTxt : "Scenario",
ResolutionsTxt : "Resolutions",
TriggersTxt : "Triggers",
menuLink : "javascript:void(0)",
subMenuLink1 : "javascript:void(0)",
subMenuLink2 : "javascript:void(0)",
subMenuLink3 :"javascript:void(0)",
createBaseEntry : function createDefault () {
this.container = $(document.createElement('div'));
this.container.addClass('gw-sidebar');
var html = "";
html += '<div id="gw-sidebar" class="gw-sidebar">';
html += '<div class="nano-content">';
html += '<ul class="gw-nav gw-nav-list">';
html += '<li class="init-un-active"> <span class="gw-menu-text">Scenarios</span> </li>';
html += '</ul></div></div></div>';
this.container.append(html);
$('body').append(this.container);
this.scenarioCount++;
this.container.append(this.createEntry(scenarioCount));
},
createEntry : function createDefault (index) {
var list = $('ul.mylist');
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(list);
return list;
},
</script>
Please advise,
Thanks!

You can make your <li> as a template and append it to the <ul> using jquery. You can try something like this Fiddle:
$(document).ready(function(){
$('a').click(function() {
var template = $('#hidden-template').html();
$('.gw-nav').append(template);
});
});

if ($(".init-un-active").length == 0) {
$.ajax({
url: 'URL From where you want to load ...',
type: 'POST',
data: { id: ID}, // pass your data here if any .. else keep empty
success: function (data) {
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
$(".init-un-active").html(data);
},
error: function () {
alert('Unable to load menu...');
}
});
}
else {
if ($(".init-un-active ul").length > 0) {
$(".init-un-active ul").css("display", "none");
$(".init-un-active").css("display", "block");
}
}
Explanation:
if ($(".init-un-active").length == 0)
This condition is used to check if there are already item loaded in li .. if yes then no need to call ajax.. just hide show that menu..
$(".init-un-active").css({ "display": "block", "z-index": "999999999999" });
this css is applied to show menu infront and hide all content beside this menu..

this.container.append(html);
$('body').append(this.container);
instead of this try this
$(".init-un-active").html(html);

Related

How can I create Nested Treeview in Mvc5 View with Ajax and JS approach

I have a simple MVC view which the department name. There is a hierarchy on the department which I use in the nested Treeview node.
My current approach shows the TREEVIEW but only stops by 1 nested.
I want to display all the existing department hierarchy in the Treeview. Something like the figure below:
> Galaxy Department
|
|___> Moon Department
|
|____> Starts Department
|
|___> Cloud department
|
|___> And so on....
My mvc View:
<div class="col-md-3" style="border:1px solid black; height:725px; background-color:#FAFAFA">
<span style="font-weight:500;">Triple4</span>
#{
<div class="treeview">
#{
if (Model != null && Model.Count() > 0)
{
<ul>
#foreach (var i in Model)
{
<li>
<span class="collapse collapsible" data-loaded="false" pid="#i.DepartId"> </span>
<span>
#i.DepatName
</span>
</li>
}
</ul>
}
}
</div>
}
</div>
My Ajax :
$(".collapsible").on("click", function (e) {
e.preventDefault();
var this1 = $(this); // Get Click item
var data = {
pid: $(this).attr('pid')
};
var isLoaded = $(this1).attr('data-loaded'); // Check data already loaded or not
if (isLoaded == "false") {
$(this1).addClass("loadingP"); // Show loading panel
$(this1).removeClass("collapse");
// Now Load Data Part1
$.ajax({
url: "/Department/GetTreeViewList/",
type: "GET",
data: data,
dataType: "json",
success: function (d) {
$(this1).removeClass("loadingP");
if (d.length > 0) {
var $ul = $("<ul></ul>");
//var result;
$.each(d, function (i, ele) {
$ul.append(
$("<li></li>").append(
"<span class='collapse collapsible' data-loaded='false' pid='" + ele.DepartId + "'> </span>" +
"<span><a href='" + ele.NavUrl + "' id='directavail' >" + ele.DepatName + "</a></span>"
)
)
});
//$("[data-role=collapsible]").trigger("collapse");
$(this1).parent().append($ul);
$(this1).addClass('collapse');
$(this1).toggleClass('collapse expand');
$(this1).closest('li').children('ul').slideDown();
}
else {
// no sub menu
$(this1).css({ 'dispaly': 'inline-block', 'width': '15px' });
}
$(this1).attr('data-loaded', true);
},
error: function () {
alert("Error!");
}
});
}
else {
// if already data loaded
$(this1).toggleClass("collapse expand");
$(this1).closest('li').children('ul').slideToggle();
}
});
Any Subjection is very welcome.
I have found a very good approach from #Sourav Mondal
TreeView on Demand
Very quick and Accurate approach which I had to some changes on a JS script since it's old.
And the link it's just a tutorial and guideline.
Hopefully, it's helping someone too.

Image.load function is not being called

I'm pretty new at JavaScript / jQuery.
The below example does call the .each part for every waterfall-item in my list. But the $img.load is never called for some reason?
Can't really figure out what I'm doing wrong?
(function($) {
$(document).ready(function(e) {
var $waterfall = $('.waterfall');
if ($waterfall.length) {
$waterfall.waterfall({});
}
// sort the waterfall when images are loaded
var $waterfallItem = $('.waterfall-item');
$waterfallItem.each(function(j, image) {
var $img = $(image);
$img.load(function() {
$waterfall.waterfall({});
});
});
});
})(jQuery);
<ul class="waterfall">
<li class="waterfall-item">
<a href="hidden link" title="hidden title">
<img alt="hidden alt" title="hidden title" data-srcset="hidden in this example" data-src="also hidden in this example" src="still hidden in this example" data-sizes="(min-width:440px) 300px, 95vw" class=" lazyloaded" sizes="(min-width:440px) 300px, 95vw"
srcset="think I'll hide this one too">
<span class="waterfallImgOverlay"></span>
</a>
</li>
</ul>
Solved it like this:
var $waterfall = $('.waterfall');
if ($waterfall.length) {
$waterfall.waterfall({});
}
// sort the waterfall when images are loaded
var $waterfall_images = $waterfall.find('img');
$waterfall_images.each(function(j, image) {
var $img = $(image);
$img.load(function() {
$waterfall.waterfall({});
});
});

Set custom attribute for autodividers

I am trying to divide a ListView that is dynamically populated in jQuery-mobile. I am setting some listitems with attribute status="true" and some to status="false", and wonder if it's possible to automatically divide these into two groups (Downloaded/Not downloaded)?
This is my HTML:
<div role="main" class="ui-content jqm-content">
<div>
<ul id="linkList" data-role="listview" data-autodividers="true">
</ul>
</div>
</div>
My JS:
var $li;
var $status = 'false';
window.resolveLocalFileSystemURL(fileSource + val.title + ".pdf", success, fail);
// if file exists
function success() {
$li.find("a").on("click", function(){ openPdf(val.title); });
$status = 'true';
}
// if file doesnt exists
function fail() {
$li.find("a").on("click", function(){ downloadPdf(val.title,val.url); });
$status = 'false';
}
$li = $("<li><a href='#' status=''+status+''>"+val.title+"</a></li>");
$("#linkList").append($li).listview('refresh');
$("#linkList").listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.attr('status');
return out;
}
}).listview('refresh');
So, is it possible to do this automatically, or do I have to do the sorting by code, and add the dividers. The code as it is doesn't add any dividers at all.
First, autodividers really only works if your list is already sorted by status. So you will want to sort it before adding it to the UL.
Next, for status you can use a data-attribute on the LI or the anchor within the li:
'<li >' + item.val + '</li>'
Then when adding the items, set the autodividersSelector to retrieve the data-attribute on the anchor:
$('#linkList')
.empty()
.append(allfiles)
.listview({
autodividers:true,
autodividersSelector: function ( li ) {
var out = li.find('a').data("status");
return out;
}
})
.listview("refresh");
Working DEMO

jQuery script for finding elements by typing and organize them

I would like to search by any term (name, user, from, price), and display the div into top and hide the ones who doesn't have the typed value.
Here's the jsfiddle: http://jsfiddle.net/Sc9ys/10/
I would like to have the same result as the jquery mobile table filter http://demos.jquerymobile.com/1.4.0/filterable/
Where you can search for any term.
I know that for search for any term I should use $(list).find("li *:)... but I can't figure out how to display the items properly. If you test my jsfiddle it doesn't work very well.
Edit: As asked by the user below, here's some more info.
<ul id='list'>
<li>
<div class='row'>
<div class='middle'>
<ul>
<li><h3>Stackoverflow</h3></li>
<li><span>User</span></li>
<li><span>London</span></li>
</ul>
</div>
<div style='clear: both'></div>
</div>
</li>
</ul>
$("#search").change( function () {
$(list).find("li *:not(:Contains(" + filter + "))").parent().hide();
});
DEMO
The idea is in
$("#ul_container").find("li").filter(function () {//your comparing logic here });
Here, try this out. Honesty I couldn't read thru your code, so I made this example. I added the sub items (spans that contain data to be searched) in an array datalist by their class name.
Generic Search Function.
HTML
<input type="text" id="search" />
<ul id="ul_container">
<li class="listItem">
<span class="car">Honda</span>
<span class="country">Japan</span>
</li>
<li class="listItem">
<span class="car">BMW</span>
<span class="country">Germany</span>
</li>
</ul>
Script:
//Capture user input
$("#search").on("keyup change", function () {
var str = $.trim($(this).val());
if (str) {
search(str);
} else {
// if no input, then show all
$(".listItem").show();
}
});
//the search part.
var datalist = ["car", "country"];
function search(toFind) {
//select all li and loop thru them one by one
$("#ul_container").find("li").filter(function () {
var $li = $(this);//hold current li in a variable
//loop thru all sub spans by their class and check if the toFind keyword is there
// you modify this step, i use it to specify which sub span to be searched. Sometimes I don't want all field to be searched, only the ones I select.
for (var i = 0; i < datalist.length; i++) {
//hold the span in a var called $item
var $item = $li.children("." + datalist[i]);
var content_str = $item.html();//get the actual string
//the comparing code
if (content_str.toLowerCase().indexOf(toFind.toLowerCase()) >= 0) {
$li.show();
break;
} else {
$li.hide();
}
}
});
}
Solved guys. Thank you all.
You can see the following example working at: http://jsfiddle.net/Sc9ys/29/
$('#search').on('keyup change', function(){
var str = $.trim($(this).val());
if (str) {
search(str, $("#list"));
} else {
$("#list").find('li').show();
/* The <li> are display: none, to show them again if the input type is clear,
we must find those <li> and show them. Showing only the #list isn't enough. */
}
});
function search(toFind, list){
$(list).find('li').filter(function() {
$li = $(this);
$li.find(".middle :contains(" + toFind +")").parent().parent().slideDown();
$li.find(".middle").not(":contains(" + toFind + ")").parent().parent().slideUp();
});
}
/* Function to search with the input lowercase */
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Edit: Made some adjustments according to the help of user #Joraid.

Retrieve Class element from Div

I am using the autodividersSelector function to display post date as divider text. I am stuck at the point of how to navigate to retrieve the date class. Below is the code and console log of the Div element in DOM.
If this question had been answered else where, please provide me with the link. Thanks
Code
$(document).on('pagebeforeshow', '#blogposts', function () {
$.ajax({
url: "http://howtodeployit.com/category/daily-devotion/feed/?json=recentstories" ,
dataType: "json" ,
beforeSend: function () {$('.loader').show();},
complete: function () {$('.loader').hide();},
success: function (data){
$('#postlist').empty();
//setTimeout(function(){
$.each(data.posts, function (key, val) {
//Format date
var dateString = val.date.split(' ')[0];
var vdate = dateString.split("-")[1] + " " + monthStrings[parseInt(dateString.split("-")[1])] + ", " + dateString.split("-")[0];
//Output data collected into page content
var rtitle = $('<p/>', {'class' : 'vTitle', html: val.title}); rdate = $('<p/>', {'class': 'vDate' , html: vdate});
rid = $('');
var rappend = $('<li/>').append(rtitle, rdate);
$('#postlist').append($(rappend).wrapInner(rid).fadeIn(600));
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
//console.log(li);
var out = $(li).get(0)
console.log(out);
return out;
}
});
return (key !== 5);
});
$("#postlist").listview().listview('refresh').append('<div class="more-posts" style="text-align: center;">Load more posts...</div>');
// }, 2000);
},
error: function (data) {
alert("Service currently not available, please try again later...");
}
});
});
Result of output showing [objectHTMLLiElement] in the divider
HTML:
<!-- Page: Blog Posts -->
<div id="blogposts" data-role="page">
<div data-role="header" data-position="fixed">
<h2>My Blog Posts</h2>
</div><!-- header -->
<div data-role="listview">
<ul data-filter="true" data-filter-placeholder='Search blog posts...' data-theme="a" id="postlist"> </ul><!-- content -->
</div>
<div class="loader"><img src="css/images/loader.gif"/></div>
</div><!-- page -->
$('.vDate').each(
function(){
alert($(this).html());
}
);
OK this is the final code that worked for custom autodividersSelector:
$('#postlist').listview({
autodividers: true,
autodividersSelector: function (li) {
var out = li.find("p").map(function() {return $(this).text();});
var out1 = out.get(1);
return out1;
}
});

Categories

Resources