skyshine
skyshine

Reputation: 2864

How to add Html element to dynamic list in jquery

I am new to web programming.Actually I want to create a list in that I have to add elements dynamically to unordered list.I added elements in list dynamically but I have to anchor tag to that each list item.please help me

HTML:

<div data-role="main" class="ui-content">        
    <input type="button" id="btnid" onclick="getData()"/>
    <p id="p1">
        Insert Content Here working
    </p>
    <ul data-role="listview" data-inset="true" id="ulist"  title="nodes list" data-inset="true">                        
    </ul>
</div>

JavaScript:

for (var i = 0; i < jsonData.Element.length; i++) {
    var counter = jsonData.Element[i];
    //console.log(counter.counter_name);
    var newelement=$("<li>"+counter.nodeName+" "+counter.activeCount+" "+counter.inactiveCount+"</li>");                    
    newelement.appendTo("#ulist");                  
    //  alert(counter.nodeName);            
}

Upvotes: 2

Views: 3915

Answers (2)

WASasquatch
WASasquatch

Reputation: 1044

Using jQuery, you can do something like the following which I quickly wrote here. Using jQuery's built in each() function which iterates through an object, or an array for you, without establishing a four loop

var list = $('#ulist'),
    urls = new Array('one.html', 'two.html', 'three.html', 'four.html'),
    i = 0;
jsonData.each(function(k,v) {

    var node = v;
    list.append("<li><a href='"+urls[i]+"' title='"+node.nodeName.+"'>"+node.nodeName+" "+node.activeCount+" "+node.inactiveCount+"</a></li>");
    i++;

});

This will iterate through the array, giving you the key, and value (v being the value which holds your array of data) and allows you to append your data.

Upvotes: 0

Jayesh Goyani
Jayesh Goyani

Reputation: 11154

Try with this.

$("<li><a href='#'>"+counter.nodeName+" "+counter.activeCount+" "+counter.inactiveCount+"</a></li>").appendTo("#ulist");

Please try with above code snippet. Let me know if you want to set URL based on your field's value.

Upvotes: 1

Related Questions