javascript - How to add number of div's in DOM based on user input -


i created simple form, user can type in numbers. , when do, number of div's(boxes) should show in browser, based on number user types in input field.

it's done in codepen.

this html.

<head>   <link href="https://fonts.googleapis.com/css?family=roboto:700"    rel="stylesheet"> </head>  <body>     <!--_-_-_-_input_field_-_-_-_-->    <div class="input-container">     <form id="inputform">      <input type="number" id="input-box" name="quantity" min="1" max="">      <input id="filldetails" name="submit" type="submit" value="add         boxes">     </form>    </div>    <!--_-_-_-_box-container_-_-_-_-->   <div class="boxes-container">     <div id="boxes"></div>   </div>  </body>  

this js

const form = document.getelementbyid('inputform'); const input = inputform.queryselector('input');  form.addeventlistener('submit', (e) => {   const boxinput = input.value;   console.log(input.value); }); 

i submit form respond console, know working.

my question(s) are:

how user input create many divs in dom user wants to?

do use loop iterate through div many times user has put in, in input field? if so, best practice?

i when user opens page, there 0 div's visible , when add number, div's show, if makes sense?

thanks :)

i have jquery's .clone() method.

create class called .hide , have set .hide { display: none; }

add square element have in html already.

what clone square x amount of times, , remove .hide class each one.

this can done so:

html:

<form class="boxform">     <input type="number" class="boxinput"/>     <input type="submit" value="submit"/> </form> <div class="boxcontainer">     <div class="box hide"></div> </div> 

css:

.box {     height: 100px;     width: 100px;     background-color: red; } .hide {     display: none; } 

js:

$(function(){      $('.boxform').submit(function(e){         e.preventdefault();         var amount = $('.boxinput').val();         for(i=0; i<amount; i++){             var newbox = $('.hide').clone();             newbox.removeclass('hide');             newbox.appendto('.boxcontainer');         }     });  }); 

jsfiddle link working same code above:

https://jsfiddle.net/panomosh/3ba9uu9o/

jsfiddle link using <ul> element requested in comments

https://jsfiddle.net/panomosh/3ba9uu9o/4/


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -