Javascript array of hrefs - javascript

I am trying to create an array with different hrefs to then attach to 5 separate elements.
This is my code:
var link = new Array('link1', 'link2', 'link3', 'link4', 'link5');
$(document.createElement("li"))
.attr('class',options.numericId + (i+1))
.html('<a rel='+ i +' href=\"page.php# + 'link'\">'+ '</a>')
.appendTo($("."+ options.numericId))
As you can see I am trying to append these items from the array to the end of my page so each link will take the user to a different section of the page. But i have not been able to do this. Is there a way to to create elements with different links?
I am new to javascript so I am sorry if this doesn't make a whole lot of sense. If anyone is confused by what i am asking here I can try to clarify if I get some feedback.
The code I would Like output is:
<ul class="controls">
<li class="controls1"></li>
<li class="controls2"></li>
<li class="controls3"></li>
<li class="controls4"></li>
<li class="controls5"></li>
</ul>
Which is similar to what I am getting, however when I apply the fix that andres descalzo has supplied, my list elements are each repeating themselves 5 times.
Any solutions would be greatly appreciated.
Thanks,
jason

I'm not sure exactly what you want, as there is some undefined values and syntax errors in your code, but here is an example on how to create elements from an array and add to an existing ul element:
$(function(){
$.each(['link1', 'link2', 'link3', 'link4', 'link5'], function(i, link){
$('<li/>')
.append(
$('<a/>')
.attr({ 'class': 'c' + i, ref: i, href: 'page.php#' + link })
.text(link)
).appendTo('ul');
});
});
With the existing ul element, it produces:
<ul>
<li><a class="c0" ref="0" href="page.php#link1">link1</a></li>
<li><a class="c1" ref="1" href="page.php#link2">link2</a></li>
<li><a class="c2" ref="2" href="page.php#link3">link3</a></li>
<li><a class="c3" ref="3" href="page.php#link4">link4</a></li>
<li><a class="c4" ref="4" href="page.php#link5">link5</a></li>
</ul>
(In place of the array literal [...] you could of course use an array variable.)

something like this?:
*Edit II * for comment
var link = ['strategy', 'branding', 'marketing', 'media', 'management'],
refNumericId = $("."+ numericId);
$(link).each(function(i, el){
$("<li></li>")
.attr("id", numericId + "_" + (i+1))
.attr("class", numericId + (i+1))
.html("")
.appendTo(refNumericId);
});
I saw your code in the file 'easySlider1.7.js' and you're including in 'for' of the line 123 the code 'var link = [' strategy,''which should go after this 'for'

Related

javascript, nested navbar from json

My aim is to replicate this structure automatically from a json file.
<ul class="sidebar-menu">
<li class="treeview">
Mammals
<ul class="treeview-menu">
<li>Goat</li>
<li> Sheep
<ul class="treeview-menu">
<li>Bone</li>
<li>Bone
<ul class="treeview-menu">
<li>Variant 1</li>
<li> Variant 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
JSON
[
{"datasetID":"5fd4124900827","higherClassification":"Eukarya","kingdom":"Animalia","phylum":"Chordata","class":"Mammalia","order":"Artiodactyla","family":"Bovidae","genus":"Capra","subgenus":"None","vernacularName":"goat","commonName":"None","elementName":"Calcaneus","commonElementName":"None"},
{"datasetID":"5fd4058e5c8d2","higherClassification":"Eukarya","kingdom":"Animalia","phylum":"Chordata","class":"Mammalia","order":"Artiodactyla","family":"Bovidae","genus":"Capra","subgenus":"None","vernacularName":"goat","commonName":"goat","elementName":"Femur","commonElementName":"None"}
]
The relevant parts are:
"datasetID":"5fd4124900827"
"class":"Mammalia",
"order":"Artiodactyla",
"family":"Bovidae",
"genus":"Capra",
"subgenus":"None",
"vernacularName":"goat",
"elementName":"Calcaneus"},
So the class is on the top level of the hierarchy, it could be mammal, bird, fish...
Taking class: Mammalia as an example, under this is order under that family under that genus
then if there is a subgenus that is on the next level also.
Under that is the vernacularName then elementName.
Each record has a unique id datasetID there may be multiple "elementName": "Calcaneus" for a goat, these need an integer added (i.e. Calcaneus 1, then Calcaneus 2, then Calcaneus 3 etc.
>Mammalia
>order
>family
>genus
>subgenus (if exists)
>vernacularName
>elementName (if more than one append 1,2,3...)
So, my mega question, how to do this in javascript?
My attempt so far:
Php gets the json, yes this could be done in javascript.
<?php
$data = json_decode(file_get_contents("bonify" . $version . "/app/json/data.json"), True);
?>
Javascript picks up the json:
<script type="text/javascript">
const version = "<?php echo $version; ?>";
$.getJSON('bonify'+ version +'/app/json/data2.json', function(json) {
console.log(json); // this will show the info it in firebug console
obj = json
This lists all the json data:
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
closing code:
});
</script>
I'm not convinced document.write is the best way to do this.
I have this code for my search and it seems like I should adapt that but with out the filter capability.
$('#txt-search').keyup(function(){
var searchField = $(this).val();
if(searchField === '') {
$('#filter-records').html('');
return;
}
var regex = new RegExp(searchField, "i");
var output = '<div class="col-12 p-0"><hr />';
var count = 1;
$.each(data, function(key, val){
if ((val.datasetID.search(regex) != -1) || (val.ownerInstitutionCode.search(regex) != -1)|| (val.vernacularName.search(regex) != -1)|| (val.elementName.search(regex) != -1)) {
output += '<ul class="sidebar-menu">';
output += '<li><i class="fas fa-bone" data-fa-transform="rotate-45"></i> <span>' + val.vernacularName + ': ' + val.elementName + '</span></li>';
output += '</ul>';
if(count%2 == 0){
output += '</div>'
}
count++;
}
});
$('#filter-records').html(output);
});
});
});
I'm assuming several nested foreach loops is the way to go? I've put the whole aim for clarity. I am trying to learn and I have a learning disability so please be patient with me, thanks for your help. I've tried to included as much info as possible to avoid having my question closed as too broad.
You have a repeated pattern. If we assume that you have built a hierarchical data structure, then we can use a function using template literals, like:
function buildChildren(children) {
var tvms = [];
for (let child of children) {
tvms.push(myTreeViewMenu(child));
}
return tvms;
}
function myTreeViewMenu(treeViewMenu) {
tvms = buildChildren(treeViewMenu.children);
return `
<ul class="treeview-menu">
<li>${treeViewMenu.name} ${tvms.join("")}</li>
</ul>
`;
}
function myTree(tree) {
tvms = buildChildren(tree.children);
return `
<ul class="sidebar-menu">
<li class="treeview">
${tree.name}
${tvms.join("")}
</li>
</ul>
`;
}
(NOT TESTED)
This logic can be a starting point for you, basically you nest your pattern into itself. You need to make sure that from your raw JSON you build an object tree whose nodes have a string called name and an array for the subtree called children. Also, make sure there are no cycles in the tree.

Framework7: Delete items of an array with swipeout

I tried app developing with Framework7.
I print my array (list) in this way:
if (list != null){
for (var i=0; i<list.length; i++){
output = output + '<li class="swipeout"><div class="item-content swipeout-content"><div class="item-inner"><div class="item-title-row"><div class="item-title">' + list[i].name + '</div></div><div class="item-subtitle">' + new Date(list[i].fDate).toLocaleDateString() + '</div></div></div><div class="swipeout-actions-right">Delete</div></li>';
}
}
$$('#liste').html(output);
When I swipeout an entry, the entry will disappear but he is still in the array.
This is to handle the remove-event:
$$('.swipeout').on('deleted', function () {
myApp.alert('Item removed');
});
How can I get the index of the element to remove it also from the array?
Alternatively, is there an other way to solve this problem?
Thank you!
Markus
If I were you, I'd rather use Framework7's view engine to render the swipeout items and take advantage of the #index helper. Click here for further information.
In your markup, you'd have something similiar to this:
<div class="list-block">
<ul>
{{#each item in list}}
<li class="swipeout">
<!-- Usual list element wrapped with "swipeout-content" -->
<div class="swipeout-content">
<!-- Your list element here -->
<div class="item-content">
<div class="item-media">...</div>
<div class="item-inner">...</div>
</div>
</div>
<!-- Swipeout actions right -->
<div class="swipeout-actions-right">
<!-- Swipeout actions links/buttons -->
<a href="#" data-index={{#index}}>Action 1</a>
<a class="swipeout-close" href="#" data-index={{#index}}>Action 2</a>
</div>
</li>
{{/each}}
Notice that I'm using the "each" helper along with "#index" to render the items and put an attribute on them with the id. But you can still achieve the same objective by using the "i" variable inside the for loop:
if (list != null){
for (var i=0; i<list.length; i++){
output = output + '<li class="swipeout"><div class="item-content swipeout-content"><div class="item-inner"><div class="item-title-row"><div class="item-title">' + list[i].name + '</div></div><div class="item-subtitle">' + new Date(list[i].fDate).toLocaleDateString() + '</div></div></div><div class="swipeout-actions-right"><a href="#" class="swipeout-delete" data-index='+i+'>Delete</a></div></li>';
}
}
When the event is fired:
$$('.swipeout').on('deleted', function () {
var $thisAction = $(this);
// Here you delete the item
delete list[$thisAction.data('index')];
myApp.alert('Item removed');
});
In this case you can't use Array.slice because if you delete item 2 from the markup, the element with the index 3 will replace item 2. The problem with the above approach is that you have to take care of the "holes" in your array. A much better approach would be to use a two-way binding framework, such as VueJs.

List items don't appear in Ul

This is my code:
$("#showing").append("<ul id='vrijemeObjava'");
for(i=0;i<App.vrijemeObjavljivanja.length;i++) {
$("#showing").append("<li><strong>" + App.vrijemeObjavljivanja[i] + "</strong></li>");
}
$("#showing").append("</ul>");
This is made inside a FB.api call. The "App.vrijemeObjavljivanja is an array of dates which I want to put in an ul. The array is put in <li></li> but not in <ul>.
The end result looks like this.
<ul id='vrijemeObjava'></ul>
<li>...</li>
<li>...</li>
<li>...</li>
Can someone please tell me why are the list items coming after the </ul>.
try this :
$("#showing").append("<ul id='vrijemeObjava'></ul>");
for(i=0;i<App.vrijemeObjavljivanja.length;i++) {
$("#vrijemeObjava").append("<li><strong>" + App.vrijemeObjavljivanja[i] + "</strong></li>");
}
(in your exemple your ul open tag is not correctly built .append("<ul id='vrijemeObjava'"); missing a > )
better version, storing the ul in a variable :
$ul = $('<ul/>', {id : 'vrijemeObjava'}).appendTo("#showing");
for(i=0;i<App.vrijemeObjavljivanja.length;i++) {
$ul.append("<li><strong>" + App.vrijemeObjavljivanja[i] + "</strong></li>");
}
When you append, you append entire elements (both the opening and closing tags). Try this instead:
$ul = $("<ul id='vrijemeObjava'></ul>");
for(i=0;i<App.vrijemeObjavljivanja.length;i++) {
$ul.append("<li><strong>" + App.vrijemeObjavljivanja[i] + "</strong></li>");
}
$("#showing").append($ul);

jquery / javascript insert ul / li elements into this html

is it possible to amend the following html into the source linked at the bottom of this page? I have limited scripting access to the source page so I'm looking for a way to change the page using jquery or js.
Also the department id's will be completely random and there will be a different number of links relative to each group, therefore it will need to be dynamic. I've tried appending but I'm having trouble as inserting starting or closing tags only, so not sure how to go about this. Thanks in advance for any help offered.
Additions I need in the code are marked with **'s
Original source:
<ul class="menu">
<a id="group-car" href="#">Car</a>
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
<a id="group-bike" href="#">Bike</a>
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
</ul>
What I need to end up with:
<ul class="menu">
**<li>**
<a id="group-car" href="#">CAR</a>
**<ul class="acitem">**
<li><a id="department-2" href="link">Black</a></li>
<li><a id="department-4" href="link">Blue</a></li>
**</ul>**
**</li>**
**<li>**
<a id="group-bike" href="#">BIKE</a>
**<ul class="acitem">**
<li><a id="department-1" href="link">BMX</a></li>
<li><a id="department-6" href="link">Racing</a></li>
<li><a id="department-12" href="link">Mountain</a></li>
**</ul>**
**</li>**
</ul>
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
jQuery(this).nextUntil("a").wrapAll("<ul></ul>");
});
jsfiddle
Does this need some explanation?
EDIT oops! I didn't see the classes on them:
jQuery(".menu").children("a").each(function()
{
jQuery(this).nextUntil("a").add(this).wrapAll("<li></li>");
var jUL = jQuery("<ul></ul>").addClass("acitem");
jQuery(this).nextUntil("a").wrapAll(jUL);
});
jsFiddle
What a beautiful challenge!!
Here you have. Tested in FF 3.6 and works!
function fixMarkup(){
var liFamilies = [];
var iFamily = 0;
$(".menu li").each(function(){
if($(this).prev().is("a"))
liFamilies[iFamily] = [this]; //Start a family
else
liFamilies[iFamily].push(this); //Append to family
if($(this).next().is("a")) iFamily++; //A new family begins
});
//console.log(liFamilies);
for(var i = 0; i< liFamilies.length; i++){
var family = liFamilies[i];
$(family).wrapAll('<ul class="acitem" />');
var ulNew = $(family[0]).parent()[0];
var aElem = $(ulNew).prev()[0];
$([aElem, ulNew]).wrapAll("<li/>");
}
}
$(document).ready(function(){
fixMarkup();
});

How to dynamically build/add list elements (ul, ol, li) using jQuery DOM manipulations?

I am programming an AJAX web page (using IE 8) and need to dynamically build a list in jQuery from the data returned. Later, I will be converting list to jQuery accordian.
I am also trying to learn the proper way to use these jQuery functions and chaining. I am just a jQuery NOOB, but understand JavaScript. I found a good article on jQuery dom functions: http://www.packtpub.com/article/jquery-1.4-dom-insertion-methods
I want to add as much as possible using the jQuery dom functions, and jQuery chaining, without resorting to HTML source code using text. I want to mostly use .wrap(), .appendto(), .attr(), .text(), and .parent().
I don't think that the ".attr("class", "CC_CLASS"). is the best way to add a class.
Given the HTML code:
<div id="outputdiv"></div>
Use jQuery dom functions to change it to be the following:
<div id="outputdiv">
<ul id="JJ_ID">
<li> AAA_text </li>
<li id="BB_ID"> BBB_text </li>
<li class="CC_CLASS"> CCC_text </li>
<li id="DD_ID">DDD_text<br/>
<ol id="EE_ID">
<li> FFF_text </li>
<li id="GG_ID"> GGG_text </li>
<li class="HH_CLASS"> HHH_text </li>
</ol>
</li>
</ul>
</div>
Some code I figured out (ignoring the spaces in text).
var aObj = $('<li></li>').text("AAA_text")
var bObj = $('<li></li>').attr("id", "BB_ID").text("BBB_text");
var cObj = $('<li></li>').attr("class", "CC_CLASS").text("CCC_text");
var dObj = $('<li></li>').attr("id", "DD_ID").text("DDD_text");
var fObj = $('<li></li>').text("FFF_text");
var gObj = $('<li></li>').attr("id", "GG_ID").text("GGG_text");
var hObj = $('<li></li>').attr("class", "HH_CLASS").text("HHH_text");
Somehow add (fObj + gObj + hObj) into eObj ?
var eObj = `*something*`.attr("id", "EE_ID").wrap(`*something*`);
Somehow add (aObj + bObj + cObj+ dObj + eObj) into jObj ?
var jObj = `*something*`.attr("id", "JJ_ID").wrap(`*something*`);
jObj.appendTo("#xmlOutputId")
The .append method returns the same container object you called it on -- make use of this to chain methods pleasantly:
var inner_list = $('<ol/>', {id: "EE_ID" })
.append( $('<li/>', {text: "FFF_text" })
.append( $('<li/>', {id: "GG_ID", text: "GGG_text" })
.append( $('<li/>', {"class": "HH_CLASS", text: "HHH_text" });
var outer_list = $('<ul/>', {id: "JJ_ID" })
.append( $('<li/>', {text: "AAA_text" })
.append( $('<li/>', {id: "BB_ID", text: "BBB_text" })
.append( $('<li/>', {"class": "CC_CLASS", text: "CCC_text" })
.append(
$('<li/>', {id: "DD_ID", text: "DDD_text"})
.append(inner_list)
);
outer_list.appendTo('#xmlOutputId');
You could actually do the entire thing in a single statement with no vars, but in my opinion that would be getting too ugly.

Categories

Resources