jeudi 14 mai 2020

HTML JAVASCRIPT: add random value to element quantity in a form

I'm a beginner in web development and I am making a bookstore website . Every book has an amount property between 1-5 (which means that if you want to buy a book you can buy the same book 1-5 times) and I have made a button that when you click it , it has to assign random values to the amount properties of each product . I have to perform this task using javascript which I am a complete beginner at . I have written some code but it doesn't work when I click the button as the amount values do not change . I would appreciate your guidance with solving the specific issue . Thank you in advance . My code :

//function that has to assign random values to amount properties
function randomfunc(){
    
    
    for(var i=0;i<2;i++){

                 document.getElementsByClass("amount")[i].value=Math.floor(Math.random()*5)+1;
                
                 
                }
                
         
        
  
  }
  //2 product instances 
  <div id="p-float">


     <div class="p-float"><div class="p-float-in">
            <center><img class="p-img" src="IMAGES\subtle.jpg" alt = subtle_art/ ><br/>
            <div class="p-name">Subtle Art of not giving an F</div>
                    <div class="p-price">$9.99</div>
                        <div class = "amount"> Amount:<input type = "number" name = "num"  value = "amount " min = "1" max = "5"/> </div><br/>
            <div class = "buyme">   <input type = "checkbox" name = "box" value = "Buy me"/> Buy Me  </div></center>
     </div></div>
      

      <div class="p-float"><div class="p-float-in">
            <center><img class="p-img" src="IMAGES\work.jpg" alt = deepw/ ><br/>
            <div class="p-name">Deep </br>Work </div>
                    <div class="p-price">$9.99</div>
                        <div class = "amount"> Amount:<input type = "number" name = "num"  value = "amount " min = "1" max = "5"/> </div><br/>
            <div class = "buyme">   <input type = "checkbox" name = "box" value = "Buy me"/> Buy Me  </div></center>
     </div></div>



  </div>
  
    <button class = "randbtn" onclick="randomfunc()"> Select random products </button> 



Aucun commentaire:

Enregistrer un commentaire