TobyGWilliams
TobyGWilliams

Reputation: 631

Setting up a button press function to trigger an Ajax call with a Id

I am trying to figure out the easiest way to set out a page that contains Ajax calls.

My primary problem is that I can write the page but when it comes to binding the event that gets run when the user clicks the button, I struggle to think of a good way to pass the id to the function to make the call and then get back to the DOM element that was pressed to let the user know it was a success.

I have created a very simplistic jsFiddle to show the problem:

Html:

<ul id="list"></ul> 

Javascript:

var Data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}];

function dothething(id){
    alert("load the ajax - but how to get the back to the element that was clicked?")    
}

for (i=0;i<Data.length;i++){
   $("#list").append(
       $("<li></li>")
           .text(Data[i].name)
           .click(function(){
               alert("How to get the id?")
               id = 1
               dothething(id)
           })
       )
}

http://jsfiddle.net/wqorcwjq/1/

What is the simplest way to complete this example?

Upvotes: 0

Views: 338

Answers (3)

n4m31ess_c0d3r
n4m31ess_c0d3r

Reputation: 3148

You can use $.each function of jquery.

$.each(Data, function(i, item){
     $("#list").append(
          $("<li></li>")
             .text(item.name)
             .click(function(){
                 alert(item.id);
                 dothething(item.id);
             })
     );
});

Upvotes: 1

Rahul Desai
Rahul Desai

Reputation: 15501

You didnt set the ID to get it in the first place. :)

Use .attr("id", Data[i].id) to set the ID.

Use event delegation to handle the click event of dynamically added li elements.

Updated jsFiddle

JS:

var Data = [{"id":1,"name":"a"},{"id":2,"name":"b"},{"id":3,"name":"c"}];

function dothething(id){
    alert("load the ajax - but how to get the back to the element that was clicked?")    
}

for (i=0;i<Data.length;i++){
    var li = $("<li></li>").text(Data[i].name).attr("id", Data[i].id);  // set li text and ID here
   $("#list").append(li);
}

// Event delegation
$(document).on("click", "li", function(){
    alert($(this).attr('id'));
    dothething($(this).attr('id'));
});

Readup:

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

You can use the data api to store the id of the li element and then use the same in the click handler

var Data = [{
  "id": 1,
  "name": "a"
}, {
  "id": 2,
  "name": "b"
}, {
  "id": 3,
  "name": "c"
}];

function dothething(id) {
  alert("load the ajax - " + id)
}

for (i = 0; i < Data.length; i++) {
  $("#list").append(
    $("<li></li>", {
      text: Data[i].name
    }).data('id', Data[i].id).click(function() {
      var id = $(this).data('id')
      dothething(id)
    }))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="list"></ul>

Upvotes: 0

Related Questions