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">
Related
how can I use array values as constant like ; aaa 500,bbb 350,ccc 25 and at last calc value 1725.
const vals = ["aaa", "bbb", "ccc"];
clength = vals.length;
i=0;
while (i < clength)
{
vals[i] = document.getElementById(vals[i]).value;
i=i+1
};
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
how can I use array values as constant like ;
aaa 500,bbb 350,ccc 25 and at last calc value 1725.
I want while loop behave like ;
aaa = 500; bbb= 350; ccc = 25;
NOTE : Please think array function as endless.(aaa,bbb,ccc is just samples)
There's many ways to do it but without changing your code much you could use a desctructive assignment:
const [aaa, bbb, ccc] = vals;
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
It would be better to use a key/value pairs though:
document.getElementById('calc').value = calc(resolveCalcValues());
function calc(vals) {
return (vals.aaa + vals.bbb) * 2 + vals.ccc;
}
function resolveCalcValues() {
return valuesOf('aaa', 'bbb', 'ccc');
}
function valuesOf(...inputIds) {
return inputIds.reduce((vals, id) => {
vals[id] = document.getElementById(id).value;
return vals;
}, {});
}
<input id="aaa" type="number" value="500">
<input id="bbb" type="number" value="350">
<input id="ccc" type="number" value="25">
<input id="calc">
You can dynamically create variables through the window object and remember to convert strings to number to calculate with them:
const vals = ["aaa", "bbb", "ccc"];
for (const val of vals) {
window[val] = +document.getElementById(val).value;
}
document.getElementById("calc").value = (aaa + bbb)*2 + ccc;
<input id="aaa" value="500">
<input id="bbb" value="350">
<input id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
Following is a more generic approach based on adding different class names to the inputs server side and doesn't involve using any ID or variables at all
function collectionSum (selector){
const els = Array.from(document.querySelectorAll(selector))
return els.reduce((a,c) => a + Number(c.value),0);
}
const combined = collectionSum('.values.combine'),
add = collectionSum('.values.add');
document.getElementById("calc").value = combined * 2 + add;
<input class="values combine" id="aaa" value="500">
<input class="values combine" id="bbb" value="350">
<input class="values add" id="ccc" value="25">
<br>
<br>
<br>
<input id="calc">
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">
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 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>
I am trying to get a popup window to display whatever was entered into the form. I have managed to get it display the Name that was entered into the form, but would also like it to display the rating given in the website (radio buttons) using only JavaScript and HTML.
<form>
<fieldset>
<legend><b>Details</b></legend>
<label>First Name </label><input id = "fname" type="text" autofocus="" placeholder="Enter first name" name = "fname"><br><br>
<label>Last Name </label><input type="text" placeholder="Enter last name"><br><br>
<label>Email </label><input type="email" placeholder="Enter valid email"> <button onclick="myFunction()">Help</button><br><br>
</fieldset>
<fieldset>
<legend><b>Rating</b></legend>
<label>Website Rating:</label>
<input type="radio" name="Rating" value="1">* (1 Star)
<input type="radio" name="Rating" value="2">* * (2 Star)
<input type="radio" name="Rating" value="3">* * * (3 Star)
<input type="radio" name="Rating" value="4">* * * * (4 Star)
<input type="radio" name="Rating" value="5">* * * * * (5 Star)<br>
</fieldset>
<fieldset>
<legend><b>Comments</b></legend>
<label>Comments on the website:</label>
<textarea name="feedback1" rows="8" cols="70"></textarea><br>
</fieldset>
<fieldset>
<legend><b>Updates</b></legend>
Do you want to receive updates via Email?<br>
<input type="checkbox" name="updateYes" value="Yes">Yes
<input type="checkbox" name="update" value="No" checked>No<br>
</fieldset>
<input type="reset" value="Reset">
<button onclick="myFunction2()" type = "submit">Submit</button>
</form>
<script>
function myFunction() {
alert("Please enter a valid Email adress into the 'Email' field");
}
function myFunction2() {
alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website ");
}
</script>
</body>
</html>
You could use querySelector for this:
var value = document.querySelector('input[name=Rating]:checked').value;
alert("Thank you for your feedback " + value + ", You have rated the website ");
Example: http://jsfiddle.net/bvaughn/kaqqsrc1/
You could also use getElementsByName:
var value;
var radios = document.getElementsByName("Rating");
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) value = radios[i].value;
}
Example: http://jsfiddle.net/bvaughn/1qqqtafu/
Get the selected radiobutton by looping over them:
function myFunction2() {
var checkedRadioButton, inputs, rating;
inputs = document.getElementsByName("Rating");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checkedRadioButton = inputs[i];
break;
}
}
if (checkedRadioButton) {
rating = checkedRadioButton.value;
}
alert("Thank you for your feedback " + document.getElementById('fname').value + ", You have rated the website " + rating);
}
https://jsfiddle.net/d5jo235p/