Tutorial :jQuery: Most efficient way to create blocks of HTML based on number of selected items?



Question:

So I have a basic HTML <select> element where a user can select a number.

What I then need to do is create some list items in an unordered list based on the number they selected.

What's the most efficient way to do that with jQuery?


Solution:1

The most efficient method may vary across browsers, but I would imagine that setting the innerHTML of a <ul> with a string of html elements would offer the best performance.

Here's a Working Demo

$("#select").change(function() {    var val = this.value,        lis = '';      for(var i=1; i <= val; i++) {      lis += '<li> Ticket ' + i + '</li>';    }        document.getElementById('list').innerHTML = lis;        });  

and HTML

  <select id="select">      <option value="1">1 ticket</option>      <option value="2">2 tickets</option>      <option value="3">3 tickets</option>      <option value="4">4 tickets</option>      <option value="5">5 tickets</option>      <option value="6">6 tickets</option>       </select>      <ul id="list"></ul>  


Solution:2

I would have a snippet of the html inside a div that is "display:none". Use JQuery to find that snippet. Then use a for loop to append a clone() of that snippet where you want it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »