Petar Mijović Petar Mijović - 1 month ago 7
Javascript Question

dynamicaly adding list item and links using javascript

I have javascript function that adds list items in html list and it works correctly. What i want is to add a link with every link item that is added dynamically. This is the code i have:

$.ajax({
url: uri1 + "?region=" + regionForSearch,
method: "GET",
dataType: "json",
data: {
region: regionForSearch
}
})
.done(function(data) {
// On success, 'data' contains a list of products.
var urifordelete = ""

$('#factories').empty();
$.each(data, function(key, item) {
// I want to add code here
$('<li>', {
text: formatItem(item)
}).appendTo($('#factories'));
});

iscrtajMapu(data);
});


What i want is to add link in every list item, link should be created like this:

var urlForLink = 'http://localhost:50758/api/factories/' + item.ID;


I am new with javascript and html. Every suggestion appreciated.

UPDATE:

This is what I have now:

enter image description here

Link leads to deleting item, so I wanted to have information that are plain text and right next to the info, link that says delete and leads to deleting like my data leads to that action now.

Answer

You can first append an <a> to the <li>, and then append that <li> to #factories. Here's the breakdown of the operations:

var li = $('<li>');
var a = $('<a>').attr('href', urlForLink).text(formatItem(item));
li.append(a);
li.appendTo('#factories');

Or you can do it in one line like (broken-up for readability):

$('#factories')
  .append( 
    $('<li>')
      .append( 
        $('<a>')
        .attr('href', urlForLink)
        .text(formatItem(item))
      )
    )

EDIT based on your update

Just add the text to <li> instead of <a>

$('#factories')
  .append( 
    $('<li>')
      .text(formatItem(item))    // <--- add text here
      .append( 
        $('<a>')
        .attr('href', urlForLink)
        .text('Delete')          // <--- add text to delete here
      )
    )