1

I'm sure there are many questions and articles on the subject, I just cant seem to find exactly what I'm looking for...

I have a form where one of the fields excepts a number (1 to 30), I the want to create x elements, where x is the number selected, all elements should have about the same HTML structure, differing only in their id's. the elements are complex, and I think I should format them using HTML/CSS, as I feel that js should only hold the business logic, sort of MVC style.

I suppose my question is two fold:

  1. Is a "philosophical" question: Is it a good idea to try and keep the "view" (format/layout/design) in the HTML/CSS and the "control" (logic) in js? I'm new to web dev, and I'm not sure of web dev architecture philosophy...

  2. Considering I want to keep formatting out of my js, how do I go about dynamically adding/duplicating HTML elements, whilst keeping the HTML in the same file where it belongs. My first thought was to create as many elements as I might need, hidden, and and show the right number of them when needed, but this can't be the best way to do this... My second thought was to use the jquery.clone() function, but this would create duplicate id's.

thanks.

pseudoDust
  • 1,336
  • 1
  • 10
  • 18

2 Answers2

1

I think you would really benefit from using a client side compositing framework (like KnockoutJs, but there are loads of others like Ember, Angular).

That way you can keep your model (viewmodel in the case of Knockout) in JavaScript and only worry about the implentation of the view in your templated HTML.

Check out the cool knockout tutorials, maybe its what you're looking for

http://learn.knockoutjs.com/

Stephen James
  • 1,277
  • 9
  • 17
0
var inputCount = paraeInt$('input').val()),
elementMarkup = $('<div class="dynamic-    div"/>');

for(var i; i < inputCount; i++){
 $('body').append(elementMarkup);
}
Ryan
  • 295
  • 2
  • 8