简体   繁体   中英

Multiply form value by X and display total in html

 <form>
 Chapter 1 - Please enter how many copys you would like <br>
 <input type="text" id="chap1"> <br><br>
 Chapter 2 - Please enter how many copys you would like <br>
 <input type="text" id="chap2"> <br><br>
 Chapter 3 - Please enter how many copys you would like <br>
 <input type="text" id="chap3"> <br><br>
 Chapter 4 - Please enter how many copys you would like <br>
 <input type="text" id="chap4"> <br><br>
 Chapter 5 - Please enter how many copys you would like <br>
 <input type="text" id="chap5"> <br><br>
  <b> Total price :  <output id = "total"> 0 </output> </b>

I'm trying to create a website in which you can order books by chapters, each chapter costs £2. I need it to multiply the value of the individual forms by 2 and then display this cost in the output. I would like to use java script in order to do this rather than jQuery.

I havent tried much as of yet as i cant find much on the subject, so any pointers in the right direction would be appreciated.

Thanks

function calc(){
    price = 2;
    fields = document.querySelectorAll("input[id^='chap']");
    tot = 0;
    for(i=0; i<fields.length; i++){
        tot += fields[i].value * price;
    }
    document.getElementById("total").innerHTML = tot;
}

This is a simple example, you can improve it

fiddle link

 <input type="text" id="chap1">
 <input type="text" id="chap2">
 <input type="text" id="chap3">
<input type="text" id="chap4"> 
<input type="text" id="chap5">
<b> Total price :  <output id = "total"> 0 </output> </b>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
var text1= document.getElementById("chap1").value;
var text2= document.getElementById("chap2").value;
var text3= document.getElementById("chap3").value;
var text4= document.getElementById("chap4").value;
var text5= document.getElementById("chap5").value;
var  total=parseInt(text1)+parseInt(text2)+parseInt(text3)+parseInt(text4)+parseInt(text5);
 document.getElementById("total").innerHTML = total*2.1;
 }
 </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM