Create ul li dynamically using jquery - javascript

I am trying to create dynamic ul and li tags with <a> inside it. I am getting firstName is not defined error.
FIDDLE
var sData= [];
var temp = {
"firstName": 'Steve',
"route": 'url'
};
sData.push(temp);
console.log(sData);
var cList = $('ul#sParts');
$.each(sData, function(i) {
var li = $('<li/>')
.appendTo(cList);
var aaa = $('<a/>')
.text(firstName[i])
.href(route[i])
.appendTo(li);
});
<div class="row">
<ul id="sParts">
</ul>
</div>

'firstName' or 'route' are properties of supercededData. So you need to define them as a part of the array.
$.each(supercededData, function(i) {
var li = $('<li/>')
.appendTo(cList);
var aaa = $('<a/>', {
text : supercededData[i].firstName,
href : supercededData[i].route })
.appendTo(li);
});
Working example : https://jsfiddle.net/rwgoxLg2/2/

Related

Get id's retrieved by data attribute using javascript from li items

JavaScript
var sessions = [];
$('.rightDiv').each(function(index) {
var session = $.trim($(this).text().slice(0, -1)).split("×");
var sessionData = [];
for (var i = 0; i < session.length; i++) {
var ids = $(this).find('li').data('id');
var s = {
subjectOrder: i,
subjectID: ids
};
sessionData.push(s);
}
var ses = {
sessionNo: index,
sessionData: sessionData
};
sessions.push(ses);
});
HTML
<ul id="form_builder_sortable_sample" class="sortable rightDiv session4 ui-sortable">
<li class="draggable" data-id="1" name="Counting" >Counting<button onclick="deleteElement(event)" class="delbtn">×</button></li>
<li class="draggable" data-id="2" name="Priorities" >Priorities" class="delbtn">×</button></li>
</ul>
JSON
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"1"}]}
My Problem
What the code above does, is retrieves the session no from the ul class: class="sortable rightDiv session4" and each id of the li from data-id.
In this case it loops fine through the li items, but it only displays the id of the first li element.
It should be:
{"sessionNo":"0","sessionData":[{"subjectOrder":"0","subjectID":"1"},{"subjectOrder":"1","subjectID":"2"}]}
Any idea what's wrong?
Since you are using $(this).find('li').data('id');, it will always return the value of first li data attribute.
Use .each() to iterate and create an array
var sessionData = [];
$(this).find('li').each(function (index, elem) {
sessionData.push({
subjectOrder: index,
subjectID: $(elem).data('id')
});
})
change:
var ids = $(this).find('li').data('id');
to:
var ids = $(this).find('li').eq(i).data('id');

Convert list of HTML element into Javascript list of object

I'm trying to convert something like this HTML snippet:
<ul>
<li><span>Frank</span><img src="pic.jpg"></li>
<li><span>Steve</span><img src="pic2.jpg"></li>
</ul>
into a JavaScript objects that contain the name and the image's url. How can I do that?
Use map() method
var res = $('ul li').map(function() { // select all li and iterate
// return as required format of array elemnt
return {
name: $('span', this).text(), // get text in span
src: $('img', this).attr('src') // get src attribute
}
}).get(); // get array from jquery object
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
UPDATE : If you want to generate an object which has key as span text and value as src attribute then use each() method and iterate over elements and generate object.
var res = {};
$('ul li').each(function() { // select all li and iterate
res[$('span', this).text().trim()] = $('img', this).attr('src');
})
console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
var objs = document.querySelectorAll('.to-js-obj li');
var objs_arr = [];
if (objs) {
for (var i = 0; i < objs.length; i++) {
var name = objs[i].querySelector('span').innerText;
var url = objs[i].querySelector('img').src;
objs_arr.push({
name: name,
src: url
});
}
console.log(JSON.stringify(objs_arr));
}
<ul class="to-js-obj">
<li><span>Frank</span>
<img src="pic.jpg">
</li>
<li><span>Steve</span>
<img src="pic2.jpg">
</li>
</ul>
Using jQuery
var $list = $('ul'), // get the list (ideally, add an ID)
$listItems = $list.find('li'); // find list items
if( $listItems.length > 0 ) { // if list items exist
var images = []; // create empty array to store objects
$.each( $listItems, function( index ) { // loop through the list items
var $item = $( $listItems[index] ); // save item as jQuery element
var name = $item.find('span').text(); // Get name from span
var imageSrc = $item.find('img').attr('src'); // Get img src
images[index] = {}; // Create new object in array
images[index].name = name; // Add name
images[index].imageSrc = imageSrc; // Add source
});
}
Returns
[Object {
imageSrc: "pic.jpg",
name: "Frank"
}, Object {
imageSrc: "pic2.jpg",
name: "Steve"
}]
You can use this:
var image_pairs = [];
$("ul li").each(function() {
image_pairs.push({
name: $(this).find("span").text(),
url: $(this).find("img").attr("src")
});
});
console.log(image_pairs);
<ul>
<li><span>Frank</span><img src="pic.jpg"></li>
<li><span>Steve</span><img src="pic2.jpg"></li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Why I cant create in DOM anchor element?

I have this javascrpt code:
for (var data in feature.data) {
if (!shownParameters[data]) continue;
var xmlString = "<a href='www.cnn.com'>Link</a>"
var elem = $.parseHTML(xmlString);
var item = $("<li>", { style: 'padding:0px;text-align:right' })
.append($('<div>')
.append($("<span>", { text: elem }).addClass("view"))
.addClass("feature-data-value"))
.append($("<div>").addClass("clear-div"));
item.appendTo('#wfs-details-list');
}
In code above I try want to create anchor link DOM element.
But in the view I get this:
Here how it looks in the view:
Any idea why I cant create in the DOM anchor link elelment?
actually, this is not true way, but resolve your issue..
for (var data in feature.data) {
if (!shownParameters[data]) continue;
var xmlString = "<a href='http://www.cnn.com'>Link</a>";
var item = $("<li>", {style: 'padding:0px;text-align:right'})
.append($('<div>').append($("<span>").append(xmlString)).addClass("view"))
.addClass("feature-data-value")
.append($("<div>").addClass("clear-div"));
item.appendTo('#wfs-details-list');
}
If you are aiming to create this:
<ul id="wfs-details-list">
<li style="padding:0px;text-align:right" class="feature-data-value">
<div class="view"><span>Link</span>
</div>
<div class="clear-div"></div>
</li>
</ul>
then this is clearer but not shorter
for (var data in feature.data) {
if (!shownParameters[data]) continue;
$("<li>", {
style: 'padding:0px;text-align:right', // belongs in a class
class: "feature-data-value"
})
.append(
$('<div>', {
class: "view"
})
.append(
$("<span/>").append(
$("<a/>", {
href: "http://www.cnn.com",
text: "Link"
})
)
)
)
.append($("<div/>", {
class: "clear-div"
}))
.appendTo('#wfs-details-list');
}

How can i get Ids from li tags using jQuery?

Here is html code :
<ul id="sortable">
<li id="attachments[183]"></li>
<li id="attachments[196]"></li>
<li id="attachments[145]"></li>
<li id="attachments[545]"></li>
</ul>
Here is JavaScript/jQuery code :
var query = {
'action' : 'save-attachment-order',
'nonce' : '8cb16e3927',
'post_id' : 89,
}
I want to get li IDs and make it this var like this
var query = {
'action' : 'save-attachment-order',
'nonce' : '8cb16e3927',
'post_id' : 89,
'attachments[183]' : 2,
'attachments[196]' : 3,
'attachments[145]' : 1,
'attachments[545]' : 4
}
Starting with this object:
var query = {
'action' : 'save-attachment-order',
'nonce' : '8cb16e3927',
'post_id' : 89,
}
You can add the ids as new properties with this:
$("#sortable li").each(function(){
query[this.id] = 0; // not sure where you're getting the values from!
});
Now that you explained that the values are supposed to represent the order, you may want to use this instead (assuming jQuery UI):
var order = $( "#sortable" ).sortable( "toArray" );
for(var i=0; i<order.length; i++) {
query[order[i]] = i+1;
}
Alnitak's answer should also work, as the the list items will be in order anyway.
var ids = [];
$('li').each(function() {
ids.push($(this).attr('id'));
});
This will add the IDs to query, with the value being the element's relative position in the list:
$('#sortable > li').each(function(ix) {
query[this.id] = ix + 1;
});
See http://jsfiddle.net/alnitak/qddc5/
try this
object.property = value;
so your code become
$('#sortable li').each(function() {
query[$(this).attr('id')]= 'vaule u want';
});
var ids = $("#sortable li").map(function(){
return this.id;
}).get();
This will fetch all the li ids as an array..

Create a nested array containing the properties of several HTML elements

If I have HTML such as this:
<ul>
<li id="id1">Some Text</li>
<li id="id2">Other Text</li>
<-- more items could be here -->
</ul>
How can I create a an array containing JSON object with the properties of each list item in the list, something like:
var itemsData = [
{
"id" : id,
"name" : name
},
{
"id" : id,
"name" : name
}
]
Where id and name equal to $(this).attr('id') and $(this).text() where $(this) refers to a single li item.
itemsData = [];
$('ul > li').each(function(){
itemsData.push({"id" : this.id, "name" : $(this).text()})
});
DEMO (see output on console)
By using .each:
var itemsData = [];
$('li').each(function() {
var $this = $(this);
itemsData.push({
id: $this.attr('id'),
name: $this.text()
});
});
console.log(itemsData);
var arr = new Array();
$("ul li").each(function(index){
arr[index]['id'] = $(this).attr('id');
arr[index]['name'] = $(this).attr('name');
});

Categories