get all elements by class name of text boxes in javascript - javascript

I have a few text boxes on my javascript page with the class of textID. So if I were to do
function UpdateTotals() {
getText = document.getElementsByClassName('textID').value;
}
All of the values will be numbers, so how do I add all of the values in this class together? Example: there are 4 text boxes, each one has the number 2 in it. I want to get 8 by adding them all together (but only the text boxes that are in that class).

One example could be using Array.prototype.reduce()
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.textContent.trim()), 0);
console.log(total); // 8
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
<div class="textID">2</div>
For INPUT elements:
const textID = document.querySelectorAll('.textID');
const total = [...textID].reduce((a, el) => a + (+el.value), 0);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
Using NodeList.forEach()
const textID = document.querySelectorAll('.textID');
let total = 0;
textID.forEach(el => total += +el.value);
console.log(total); // 8
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">
<input class="textID" type="number" value="2">

Try this code:
HTML code:
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<input type="checkbox" class="textID" name="qty" value="2"/> 2<br>
<br><br>
Total : <input type="text" name="total" id="total"/>
Sum
JS code:
window.sumInputs = function() {
var inputs = document.getElementsByClassName('textID'),
result = document.getElementById('total'),
checkboxes = document.querySelectorAll(`input[name="qty"]:checked`),
sum = 0;
for(var i=0; i<checkboxes.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
Try it in jsfiddle : https://jsfiddle.net/u62tyj45/

Related

document.querySelectorAll('') How does it works?

I would like some tips about JS querySelectorAll('').
I need to count some checkboxes to establish a maximun of selection. The problem is I dont want to count them all the checked, just the ones with the 'name=homeCheck' and in the way I'm using querySelectorAll it's not working fine:
function insertDeleteNews(data) {
if (checked == true && document.querySelectorAll('input[type="checkbox"]:checked').length > 6){
...}
}
<td><input type="checkbox" name="homeCheck" id="homeCheck_<?=$row['id']."_".$row['id_azienda']?>" value="<?=$row['id']."_".$row['id_azienda']?>" <?= $rowHome ?"checked":""?> <?= !$rowNews ?"disabled":""?> onclick="insertDeleteNews(this.value)"></td>
You can query for the name-property instead of the type-property:
input[name="name1"]:checked
General example:
let button = document.getElementById('button');
button.addEventListener('click', function(event) {
event.preventDefault();
let count = document.querySelectorAll('input[name="name1"]:checked').length;
console.log(count);
});
<input type="checkbox" name="name1"> Name1 (1)<br>
<input type="checkbox" name="name2"> Name2 (1)<br>
<input type="checkbox" name="name1"> Name1 (2)<br>
<input type="checkbox" name="name2"> Name2 (2)<br>
<input type="checkbox" name="name1"> Name1 (3)<br>
<button id="button">Count Name1</button>
Example - limit to max 3 checked:
let checkboxes = document.querySelectorAll('input[name="homeCheck"]');
for (let checkbox of checkboxes) {
checkbox.addEventListener('click', checkboxLimitTo3Checked);
}
function checkboxLimitTo3Checked(event) {
let checked = document.querySelectorAll('input[name="homeCheck"]:checked').length;
if (checked > 3) {
event.preventDefault();
}
}
<input type="checkbox" name="homeCheck"> homeCheck 1<br>
<input type="checkbox" name="homeCheck"> homeCheck 2<br>
<input type="checkbox" name="homeCheck"> homeCheck 3<br>
<input type="checkbox" name="homeCheck"> homeCheck 4<br>
<input type="checkbox" name="homeCheck"> homeCheck 5<br>
You can replace your function by
function insertDeleteNews(data) {
if (document.querySelectorAll('input[name="homeCheck"]:checked').length > 6){
...}
}
This will find all the checked inputs with name = "homeCheck"

add additional value to the total

I am looking for a way to add the value from (discount) and (quantity) to my total. As for discount part, the customer will need to enter the right code to receiver discount. And for quantity, when clicked at the checkbox, then change the quantity, the total will also follow. Can you guys help me out on this problem?
thanks
(sorry, my English is not good)
function addItemPrice() {
var total = 0;
var count = 0;
for (var i = 0; i < document.myform.item.length; i++) {
if (document.myform.item[i].checked) {
total = (total + document.myform.item[i].value * 1); // another way to convert string to number
count++;
}
}
return total;
}
var sh_prices = new Array();
sh_prices["standard"] = 10;
sh_prices["express"] = 20;
function getAddShipping() {
var shippingPrice = 0;
var theForm = document.forms["myform"];
var shipping = theForm.elements["shipping"]
for (var i = 0; i < shipping.length; i++) {
if (shipping[i].checked) {
shippingPrice = sh_prices[shipping[i].value];
break;
}
}
return shippingPrice;
}
function getCode() {
var theForm = document.forms["myform"];
var discode = theForm.elements["discount"]
if (discode == "UAC123") {
alert("yes");
} else {
alert("no")
}
}
function getTotal() {
var totalPrice = getAddShipping() + addItemPrice();
document.getElementById('Price').innerHTML = "the total price" + totalPrice;
}
<form name="myform">
Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity"><br> Sickle $1 <input type="checkbox" name="item" value="1" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $50 <input type="checkbox" name="item" value="50" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $5 <input type="checkbox" name="item" value="5" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Sickle $7 <input type="checkbox" name="item" value="7" onclick="getTotal(item)">
<input type="number" name="quantity" value="1"><br> Standard
<input type="radio" name="shipping" value="standard" onClick="getTotal(shipping)" /> Express
<input type="radio" name="shipping" value="express" onClick="getTotal(shipping)" /> <br> Discount code
<input type="text" name="discount" size=15>
<input type="button" id="code" value="check" onClick="getCode(code)">
<div id="Price">
</div>
</form>

Create array with increased value

I have on page some elements with id`s with number of row in the end. For example
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
i know elements count, and i`m need make js array with key from productidX value, and value sum of values qtyX
i tryed like that
var out = [];
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val())
}
but this is not working(
i`m need somesing like taht
[4931] => 7
[4942] => 1
can someone say me right way for this?
sorry for mistakes, english not my native language
Try to use a object {} like this example:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
}
You also need verify if is undefined before use += like this:
var out = {}; //change to a object
var tot = jQuery('#totitems').val();
for(var i = 1; i <= tot; i++)
{
//now you can acess like properties/hashmap
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#devQty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#devQty'+i).val());
}
You also have a little mistake using #devQty instead #qty and you need to parse the tot var:
var out = {}; //change to a object
var tot = parseInt(jQuery('#totitems').val());
for(var i = 1; i <= tot; i++)
{
if(out[jQuery('#productid'+i).val()])
out[jQuery('#productid'+i).val()] += parseFloat(jQuery('#qty'+i).val());
else
out[jQuery('#productid'+i).val()] = parseFloat(jQuery('#qty'+i).val());
}
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--For testing-->
<input type="hidden" name="totitems" id="totitems" value="3">
<input type="hidden" name="productid1" id="productid1" value="4941">
<input type="hidden" name="qty1" id="qty1" value="2">
<input type="hidden" name="productid2" id="productid2" value="4942">
<input type="hidden" name="qty2" id="qty2" value="1">
<input type="hidden" name="productid3" id="productid3" value="4941">
<input type="hidden" name="qty3" id="qty3" value="5">
This is another way to do this:
var out = {};
jQuery("[name='product']").each(function(){
var value = parseFloat(jQuery(this).val());
var productID = jQuery(this).data("id");
if(out[productID])
out[productID] += value;
else
out[productID] = value;
});
console.log(out);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="product" data-id="4941" value="2">
<input type="hidden" name="product" data-id="4942" value="1">
<input type="hidden" name="product" data-id="4941" value="5">

Trying to get all input value into string, jquery or javascript

I am trying to use jquery or javascript get all input value into a string (1,2,3,4) and ignore empty value. Thank you.
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
// string to keep the result
var output = "";
// iterate over all inputs with class 'as_sym' inside the '#sym_form'
$('#sym_form > input[class=as_sym]').each(function(){
// only inputs with non-empty values
if ($(this).val() != "") {
// the first value doesn't have a comma in front of it
// subsequent values do have a comma in front of them
if (output == "") {
output += $(this).val();
} else {
output += "," + $(this).val();
}
}
});
// here do whatever you want with the 'output' variable
const form = document.getELementById("sym_form");
for (var element of form.elements) {
if(element.nodeName === "INPUT" && element.value) {
// do something with element.value
}
}
var $inputs = $('#sym_form .as_sym');
var result ="";
$.each($inputs, function(i, v) {
var val = $(this).val();
result += val;
});
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>
<p id="result"></p>
You can use .querySelectorAll() to select all "#sym_form .as_sym" elements, Array.prototype.forEach(), Function.prototype.call() to attach input event to each element, at input event concantenate values of each "#sym_form .as_sym" element to a string, use .split(), .join() to include comma , character between each character or resulting string
var inputs = document.querySelectorAll("#sym_form .as_sym");
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener("input", function(e) {
for (var i = 0, val = "", len = inputs.length; i < len; i++) {
val += inputs[i].value;
}
console.log(val.split("").join(","))
})
})
<form id="sym_form">
<input type="text" class="as_sym" id="sym_1" value="1">
<input type="text" class="as_sym" id="sym_2" value="2">
<input type="text" class="as_sym" id="sym_3" value="3">
<input type="text" class="as_sym" id="sym_4" value="4">
<input type="text" class="as_sym" id="sym_5" value="">
</form>

Dynamically, check radio button with for loop

I'm trying to create a 5 star radio picker.
This is the 1 of the radio buttons:
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
After the method gets called and "3" is passed on this is my javascript function:
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
When I run the code, it does not perform the checked to = true, though if remove the for loop, it works just fine.
Any ideas why the for loop is preventing from checking the radio boxes?
This is my entire code:
<script>
function check(stars)
{
for(i = 0 ; i < stars; i++)
{
document.getElementById("num_" + stars + "_star").checked = true;
}
}
</script>
<form>
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
</form>
Thanks!
i had to be 1 initially as ids are starting from 1
Also reset all the checked status when click is initiated! Use i instead of stars in getElementById
Try this:
function check(stars) {
for (var j = 1; j <= 5; j++) {
document.getElementById("num_" + j + "_star").checked = false;
}
for (var i = 1; i <= stars; i++) {
document.getElementById("num_" + i + "_star").checked = true;
}
}
<input onclick="check(1)" type="radio" name="one" id="num_1_star" value="1">
<input onclick="check(2)" type="radio" name="two" id="num_2_star" value="2">
<input onclick="check(3)" type="radio" name="three" id="num_3_star" value="3">
<input onclick="check(4)" type="radio" name="four" id="num_4_star" value="4">
<input onclick="check(5)" type="radio" name="five" id="num_5_star" value="5">
Put var before the iteration variable i. You are creating a global variable.

Categories