jquery - Displaying divs inside container in dynamic number of rows -


i want display divs in rows. user chooses number of divs , want display them in rows number depends on number of divs. example if user picked 6 want have 2 rows 3 divs, if picked 12 want 3 rows 4 divs etc

here have: jquery:

$("button").click(function(){ $('#container').html(''); var k=$('select').val(); for(var i=0;i<k;i++) {     $('#container').append('<div class="square"></div>'); } }); 

css:

#container{ border-style: solid; float:left; } .square{     float:left;     width: 100px;     height: 100px;     background-color: red;     margin-top: 10px;     margin-left: 10px;     margin-right: 10px;     margin-bottom: 10px; } 

html:

<select>   <option value="6">6</option>   <option value="8">8</option>   <option value="12">12</option> </select> <button>ok</button> <div id='container'></div> 

jfillde: https://jsfiddle.net/nrh1tzd1/

how can order divs in rows?

edit:

i figured out add < br> when want end row. have 1 question it. have code:

$(document).ready(function(){  $("button").click(function(){ $('#container').html(''); var k=$('select').val();  contained_divs = '';  for(var i=0;i<k;i++)  {     contained_divs += '<div class="square"></div>';     if(i!=0 && i%2==0)     {         contained_divs += '<br>';     }     } $('#container').append(contained_divs); });  }); 

here updated jfiddle: https://jsfiddle.net/nrh1tzd1/2/

and works, ends row after displaying 3 divs. don't understand how works exactly.

inside if have

i%2==0  

so starts new row after 3 divs, why doesnt start third row after displaying 2 divs in second row. variable equal 4 should. when inside if use just

i==2 

then doesn't work want to.

you should using append function in concatenation way this:

$("button").click(function(){     $('#container').html('');     var k=$('select').val();     var contained_divs = '';     for(var i=0;i<k;i++)     {         contained_divs += '<div class="square"></div>';      }     $('#container').append(contained_divs); }); 

updated jsfiddle version: jsfiddle


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -