0

Let's say I have an array of Customer structures and I need to generate HTML from it.

Currently I do something like this:

jQuery.each(customers, function(index, item) {
     html =+ "<tr custID='" + item.ID + "'><td>" + item.Name + "</td><td>" + item.City + "</td></tr>";  
});

The issue here is that I manually add the custID attribute. I believe the cool way to do this would be using jQuery's Data function.

But how would I use it in this scenario?

3
  • 1
    just google for javascript template engines or MVVM javascript frameworks. Commented Jul 30, 2012 at 22:00
  • I've used api.jquery.com/tmpl in the past. Works pretty well. Commented Jul 30, 2012 at 22:03
  • It would be cool to use a template engine and not generate html by concatenating strings in js. Commented Jul 30, 2012 at 22:05

3 Answers 3

2

The elegant way is not to append those html tags as if they are text, but create element using

document.createElement("tr");

you can modify its attributes and then append it to the html file.

Read more here:

jQuery document.createElement equivalent?

Sign up to request clarification or add additional context in comments.

Comments

1

Just prefix the attribute with data-:

jQuery.each(customers, function(index, item) {
  html += "<tr data-custID='" + item.ID + "'><td>" + item.Name + "</td><td>" + item.City + "</td></tr>";  
});

Now you can access the data using the methods in jQuery.

(I changed the non-existing =+ operator to +=. Guess it was just a typo in the question.)

Comments

0

You can use data grid i think it is much cooler than manually creating tables. But in your case you have to use append() function.

Here is good examples: http://jquery-howto.blogspot.com/2009/02/add-table-row-using-jquery-and.html http://api.jquery.com/append/

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.