简体   繁体   中英

cant calculate sum of all inputs

I need to calculate the sum of all inputs and display it in the last input. I think the error is in "input.setAttribute ('class', '.qty1');". I assigned the class incorrectly, maybe I'm wrong. Everything worked until the bottom script was added. Please, help me.

 const names = ["Penny", "Howard", "Raj", "Leonard", "Sheldon", "Rajh"] $(document).on("change", ".qty1", function() { var sum = 0; $(".qty1").each(function(){ sum += +$(this).val(); }); $(".total").val(sum); }); function inputs(){ var form = document.getElementById("myForm"); for(var i=0; i<names.length; i++) { var label = document.createElement('label'); label.setAttribute('for', names[i]); label.innerText = names[i]; form.appendChild(label); var input = document.createElement('input'); input.type = 'text'; input.name = 'myInput_'+i; input.setAttribute('class', 'qty1'); input.id = 'myInput_' + i; form.appendChild(input); } var input = document.createElement('input'); input.type = 'text'; input.name = 'myInput_'; input.setAttribute('class', 'total'); input.id = 'sum'; form.appendChild(input); document.getElementById('sum').disabled = true; }
 input { display: block; } input.total { margin-top: 30px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body onload = "inputs()"></body> <div id='myForm'></div>

remove the . from class name, it input.setAttribute('class', 'qty1'); and not input.setAttribute('class', '.qty1');

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