0

I'm looking for the best way to build some HTML 'objects' based on an array of jQuery objects that I have created. I then need each one to be clickable, and pull the values from the one that was clicked.

A bit of background...I'm building the objects from ajax calls to a external API service. The user searches for a name, then I end up with an array of objects with three properties (Id, ImageUrl, and Name).

I'm wondering if there is a 'easy'/clean way to display the Name and Image of the object and make it clickable...then when the object is clicked, I want to pass that Id back to the controller, which will in turn display a details page for the selected object.

What I currently have is all the jQuery to build the object, and then a results section:

<div id="results"> </div>

Then in the jQuery I call a function that appends to the div tag:

var div = $("<div class='well clearfix'>");
div.append($("<h4>").html(item.name));

I think the main concern is how to build the div tag in such a way that I can easily retrieve the Id of the object once it is clicked and pass it back to the controller.

3
  • Have you tried anything? Take it a step at a time, and then ask when you can not get a step working. Commented Dec 4, 2013 at 4:29
  • 1
    try data- attributes, read with jquery data() method Commented Dec 4, 2013 at 4:31
  • thanks on the data() method too...I originally thought it was for retrieving for some reason and never saw it could be used to store data along with the element. Commented Dec 4, 2013 at 5:13

1 Answer 1

1

Use data() to hold the item id, and event delegation to handle the click event

var $div = $('<div />', {
    'class': 'well clearfix item'
}).data('id', item.id);
$('<h4 />', {
    'html': item.name
}).appendTo($div);
//more contents

$div.appendTo('#results');

to handle the click event (need to be done in dom ready handler)

$('#results').on('click', '.item', function () {
    var id = $(this).data('id');
    console.log('id:', id)
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.