Reputation: 1979
I have a partial view that is updated with info from an AJAX request every time you click on an HTML element. The partial view holds a profile of a person, and has a bunch of different HTML elements (Name, Age, etc.)
I have about 20 different elements that I have to update on click - right now I manually set an ID for each one (e.g. #prof_name, #prof_age, #prof_gender, etc). Needless to say it looks pretty bad and sloppy.
Is there a more efficient way to update a ton of HTML elements?
Upvotes: 2
Views: 717
Reputation: 1440
I don't think jquery is the tool you are looking for. This is a job for an observable. You may want to try Knockout JS. http://knockoutjs.com/
When a knockout variable changes the DOM is automatically updated. They also have lots of form methods that you may want to use.
<div data-bind="text: name"></div>
var myController = function()
{
var self = this;
this.name = ko.observable();
$.ajax().done(function(data)
{
self.name(data.name);
});
};
Upvotes: 1
Reputation: 347
Personaly I would go with {{ mustache }} templates, other than this jQuery offers a .each() function. https://api.jquery.com/each/
Iterate over a jQuery object, executing a function for each matched element.
Example:
<ul>
<li>Jack Sparrow</li>
<li>33</li>
<li>Male</li>
</ul>
function updateDate(arr){
$( "li" ).each(function( index ) {
$( this ).html(arry[i]);
});
}
var el = document.getElementById("clickableElement");
el.addEventListener("click", function(){
var response = {
'name': 'Jack Sparrow',
'age': 34,
'gender': 'Male'
}
updateDate([response.name, response.age, response.gender]);
});
Upvotes: 1
Reputation: 42
Yes. You can use classes instead of IDs.
Then you can do
$(".class_name").method()
This will apply "method" to all elements that have "class_name" as class.
Upvotes: 1
Reputation: 9284
I agree with @Arthur
You can find templates in underscore and mustache
Upvotes: 1
Reputation: 5651
jQuery templates used to be a thing, but you might also check out this discussion about other options. Backbone is a popular library for this, but as you'll discover there are plenty of alternatives.
In short, it sounds like a template library is going to be a far cleaner solution than manually updating HTML through jQuery.
Upvotes: 2