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">
Related
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>
I'm trying to get the total amount from input value with pure JavaScript but It's returning blank. The format of the amount value for each input is as follow 0.00
PHP
//rest of code
$i = 0;
while ($row = mysqli_fetch_array($result)) {$i++;
<input id="Amount'.$i.'" name="Amount" value="'.$plan['price'].'" type="text">
}
echo ' <input id="total" name="finalResult" value="" type="text">';
JS
function totalResult(){
var arr = document.getElementsByName('Amount');
var total=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
total += parseInt(arr[i].value);
}
document.getElementById('total').value = total;
}
Use HTML5's query selctor API querySelectorAll() like the following:
function totalResult(){
var arr = document.querySelectorAll('input[name=Amount]');
var total=0;
arr.forEach(function(item){
if(parseInt(item.value))
total += parseInt(item.value);
});
document.getElementById('total').value = parseFloat(total).toFixed(2);
}
totalResult();
<input id="Amount1" name="Amount" value="10.00" type="text" />
<input id="Amount2" name="Amount" value="20.00" type="text" />
<input id="Amount3" name="Amount" value="30.00" type="text" /><br>
Result:
<input id="total" name="finalResult" value="" type="text">
I have a form with multiple input fields:
<input name="a1"/>
<input name="a2"/>
<input name="a3"/>
All field names are the same with an added digit.
I need JavaScript to read these values into an array.
for i = 1 to 3
a(i) = form(i)
next
Complete code:
var listC = [ "C", "A", "B" ];
a1 = form.a1.value;
a2 = form.a2.value;
a3 = form.a3.value;
if (listC[0] == a1.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
if (listC[1] == a2.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
if (listC[2] == a3.toUpperCase()) {
NumCorrect = NumCorrect + 1
}
<input type="text" size="2" name="a1" size="2"/>
<input type="text" size="2" name="a2" size="2"/>
<input type="text" size="2" name="a3" size="2"/>
Not sure if this is what you're after.
var a = [],
inputs = document.querySelectorAll('[name^="a"]');
[].forEach.call(inputs, function(input){
a.push(input.value);
});
console.log(a);
<input name="a1" value="a111"/>
<input name="a2" value="a222"/>
<input name="a3" value="a333"/>
You can do this by adding 'id' attribute similarly 'name' Like,
HTML
<input id="name1" name="name1">
<input id="name2" name="name2">
Javascript
var formData = [];
for(var i=1 ; i<length; i++){
formData.push($('#name'+i).val());
}
Without knowing the form structure you could retrieve it with vanilla javascript as follows:
var arr = [];
var currentElementIndex = 1;
while(document.getElementsByName('a'+currentElementIndex)) {
arr.push(document.getElementsByName('a'+currentElementIndex).value);
currentElementIndex++;
}
Assuming id's are >= 1 and sequential.
I have the below input fields of a processed order form in which:
Order date is given on the name field as array
Cost is given on the value field
<input type="hidden" name="09-15-2017[]" id="dateprice[]" value="1">
<input type="hidden" name="09-13-2017[]" id="dateprice[]" value="3">
<input type="hidden" name="09-13-2017[]" id="dateprice[]" value="4">
<input type="hidden" name="09-15-2017[]" id="dateprice[]" value="5">
The output im trying to get as an alert is:
Total amount on 09-13-2017 is 7
Total amount on 09-15-2017 is 6
This what im currently trying:
var chkprice = 0;
var chkdate = 0;
var inps = document.getElementsByID('dateprice[]');
for (var i = 0; i <inps.length; i++)
{
var inp=inps[i];
var chkprice = inp.value;
if(chkdate==chkdate)
{
chkprice +=chkprice;
}
alert("Total amount on "+chkdate+""+chkprice);
alert(chkprice);
}
I know i have done a terrible javascript scripting.
Can any one guide me in getting values as shown above?
Working fiddle.
First of all the id attribute should be unique in the same document so you could use the common classes instead like :
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="3">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="4">
<input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
Then you could use an object to store the some using the name of inputs as key like :
var inps = document.querySelectorAll('.dateprice');
var totals = {};
//Sum calculation
for (var i = 0; i <inps.length; i++)
{
totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value);
}
//Result display
for (var key in totals) {
if (totals.hasOwnProperty(key)) {
console.log("Total amount on " + key + " is " + totals[key]);
}
}
NOTE : You coudle remove the brackets [ ] from the output using replace() like :
console.log("Total amount on " + key.replace('[]','') + " is " + totals[key]);
Hope this helps.
var inps = document.querySelectorAll('.dateprice');
var totals = {};
//Sum calculation
for (var i = 0; i <inps.length; i++)
{
totals[inps[i].name] = (totals[inps[i].name] || 0) + Number(inps[i].value);
}
//Result display
for (var key in totals) {
if (totals.hasOwnProperty(key)) {
console.log("Total amount on " + key + " is " + totals[key]);
}
}
<input type="hidden" name="09-15-2017[]" class="dateprice" value="1">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="3">
<input type="hidden" name="09-13-2017[]" class="dateprice" value="4">
<input type="hidden" name="09-15-2017[]" class="dateprice" value="5">
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>