I am trying to calculate a ticket total based on user input on a form using 2 dimensional names. I have been searching for 2 days on how to pull all the values at once from each key in the input field names.
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
<input type="text" name="service[]['qty']">
<input type="text" name="service[]['part_number']">
<input type="text" name="service[]['price']">
When the user enters the price in the corresponding area, the total for the whole order needs to be calculated and displayed at the bottom of the screen using javascript / jQuery.
Here is the function :
function calculate_ticket(){
var total = 0;
var data = $("input[name^='service[]']").serializeArray();
$.each(data, function(i, field){
$("#ticket_total").append(field.name + ":" + field.value + "<br />"); // for debugging.
});
console.debug(data);
$('#ticket_price').html("$" + total.toFixed(2));
}
What I am hoping to do is pull all the data from each key at once and simply multiply the 'price' by the 'qty' then add that to the 'ticket_price'. The form 'service' input area can have and unlimited number of entries.
I figured a way to do this finally :)
I switched around the name dimension from service[]['qty'] to service['qty'][] and used .serializeArray() on both qty and price. Here is the function :
function calculate_ticket(){
var total = 0;
var price = $("input[name^='service[\\'price\\']']").serializeArray();
var qty = $("input[name^='service[\\'qty\\']']").serializeArray();
$.each(price, function(i, field){
total += qty[i].value * field.value;
});
$('#ticket_price').html("$" + total.toFixed(2));
}
Related
I am trying to do a shopping cart where I want the total to automatically change after the quantity is inputted (the total is the price times the quantity). I'm trying to use Javascript for this and I just can't seem to get it as it is coming up with null and before it said NaN.
PS: It is a console log at the moment just to see if it works, but I will need it to go into the total input tag.
HTML:
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="$18.95">
JavaScript:
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total = price * quantity;
console.log(total);
}
Try this:
function calcTotal() {
// remove $ sign and parse Float price
var price = parseFloat(document.getElementById("price").value.substr(1));
// parse float quantity
var quantity = parseFloat(document.getElementById("quantity").value);
var total = price * quantity;
//pass calculated value to input with id total
document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">
Any operation that involves a string returns NaN, however you should
coerce your input values as Number
function calcTotal() {
var price = document.getElementById("price").value;
var quantity = document.getElementById("quantity").value;
var total =Number(price) * Number(quantity);
console.log(total);
}
Using Number vs parseFloat
So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):
parseFloat('1x'); // => 1
Number('1x'); // => NaN
Currently i have developed a program that gets the count of all the inputs field and adding up a percentage for the numbers of fields that are filled individually.
what i need now here, i need to assign a number to each input field and when the user fills an input field i need to show it to the user as a " SCORE ".
below is the program i have built.
<html>
<body>
<label> Name </label>
<input class="track"/>
<label> Name </label>
<input class="track"/>
<h5>Profile Strength <span class='perc'>0</span>%</h5>
</body>
</html>
and the JavaScript is
<script>
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
so when you fill the first input field the 'Profile strength' will show 50% as there are only 2 input fields, and when you fill the second input it will show 100%.
i want to show a number instead of a percentage here like
input 1 = 10
input 2 = 20
so when the user fills input 1 his "SCORE" will be 10,
and when the user fills the next input the total must add on and show 30 in real time.
sorry if have confused a few developers but this the only way i understood the assignment i got.
Try the following:
Html:
<html>
<body>
<label> Name </label>
<input class="track" data-score=10 />
<label> Name </label>
<input class="track" data-score=20 />
<h5>Profile Strength <span class='perc'>0</span>%</h5>
<h5>Score <span id="score">0</span></h5>
</body>
</html>
JS:
$('.track').change(function(e) {
update_progress();
});
// supports any number of inputs and calculates done as %
function update_progress() {
var score = 0
$('input.track').each(function(){
var _score = $(this).data("score")
if ($(this).val().length > 0) {
score += _score
}
})
$('#score').text(score)
var count = $('.track').length;
var length = $('.track').filter(function() {
return this.value;
}).length;
var done = Math.floor(length * (100 / count));
$('.perc').text(done);
$('.meter').width(done + "%");
}
Or, a live version https://jsfiddle.net/wmt6cznh/2/
Is this what you want to achieve?
I have been trying to set up a kind of search engine connected to an API. It takes the user input and gives back the information from the API. In the future there should be a "dynamic" amount of input fields but for the moment I am working with a fixed amount of five. The loop takes the amount of fields and calls the API that amount of times with that input.
I tried placing a constant (i.e. 5) in the loop but still, the funny part is that with 3 it of course calls the app three times but outputs 6 fields, and with 2 it calls the API 2 times but outputs three rows so it seems that it does not obey the loop but something else. Meanwhile in the console (with log) I can see that the API is properly called only the times defined by the loop so I believe something goes wrong at the $.getJSON level
The problem is at the end a table is created with 15 rows instead of the expected 5 (one row for every input). Why do you think this is happening?
Thanks in advance
<form name="inputform" method="get" width="50">
<input type="text" name="field0" id="field0" size="50">
<input type="text" name="field1" id="field1" size="50">
<input type="text" name="field2" id="field2" size="50">
<input type="text" name="field3" id="field3" size="50">
<input type="text" name="field4" id="field4" size="50">
</form>
<table id="table">
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
<th>Preference</th>
</tr>
</table>
<input id="getInfo" type="button" value="Submit" /><br/>
var customURL = "http://apitest.com/test/";
var customURL1 = '';
$('#getInfo').click(function() {
$('#table tr').not(':first').remove();
var fields = document.getElementsByTagName('input');
var table = document.getElementById('table');
if (localStorage.myJSON !== undefined) {
var myJSON = JSON.parse(localStorage.myJSON);
}
var html = '';
for (var i = 0; i < elements.length - 1; i++) {
customURL1 = customURL + document.getElementById('field' + i + '').value;
console.log(customURL1);
$.getJSON(customURL1, function(data) {
console.log(data);
html += '<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>';
$('#table tr').first().after(html);
Each time you get an AJAX response, you're appending the response to the html variable, and then adding that after the first row of the table. Since the html variable already contains the results from the previous responses, and they were insert into the table already, you get duplicates.
Instead of concatenating the new row to html, just insert the new row directly into the table.
$.getJSON(customURL1, function(data) {
console.log(data);
$('#table tr').first().after('<tr><td>' + data.sample_list.id + '</td><td>' + data.sample_list.name + '</td><td>' + data.sample_list.age + '</td><td>' + data.sample_list.preference + '</td></tr>');
I have a field in my page named as "myField" Now this is dynamic So there are 2 cases i.e. it can be just 1 field as;
<input type="text" name="myField" />
OR there can be 2 fields as below;
<input type="text" name="myField" />
<input type="hidden" name="myField" />
I use the following code to access the value in JS;
document.forms[0].myField[0].value
However, this does not work if there is only 1 field (as in the first case)
How do I write dynamic JS code to handle the same? It should be cross browser compatible.
document.getElementById("btn").addEventListener("click", function() {
var texts = document.getElementsByName("n");
var sum = "";
for( var i = 0; i < texts.length; i ++ ) {
sum = sum + texts[i].value;
}
document.getElementById("sum").innerHTML = sum;
});
<input type="text" name="n"/>
<input type="text" name="n"/>
<p id="sum"></p>
<button id="btn"> Get Sum</button>
or Visit :How get total sum from input box values using Javascript?
On first glance of that particular example, it seems odd that those two fields have the same name. Normally one would expect the same name for fields that are mutually-exclusive, or that are the same type and form a list.
But you can still work with them: I wouldn't use the automatic properties, since as you've discovered they're inconsistent (document.forms[0].myField will be the field when there's only one, but a collection of fields with the same name if there's more than one). I'd use querySelectorAll:
var fields = document.querySelectorAll('[name="myField"]');
fields will reliably be a list. You can access the elements of that list using fields[0] and such, and get the length from fields.length.
var fields = document.querySelectorAll('[name="myField"]');
for (var n = 0; n < fields.length; ++n) {
console.log("fields[" + n + "].value: ", fields[n].value);
}
<input type="text" name="myField" value="the text field"/>
<input type="hidden" name="myField" value="the hidden field"/>
Good day,
I have 3 text fields for input.
TotalWeight
CustomUnitWeight
CustomsNumberOfUnit
There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).
I started playing around trying to construct a function for validating this no luck and looking for assistance
Scenario :
User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.
HTML
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />
JAVASCRIPT
$(function(ChkWeight){
$('#CustomsUnitWeight').click(function() {
var TotalWeight = document.getElementById('TotalWeight');
var CustomUnitWeight = document.getElementById('CustomsUnitWeight');
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');
var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;
if (TotalWeight != TotalCustomWeight) {
error message "pkg weight does not match total custom weight"
}
});
});
Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like
<body>
<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onblur="CheckWeight()" />
//I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
</body>
<script type="text/javascrit">
function CheckWeight()
{
var TotalWeight = document.getElementById('TotalWeight').value;
var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value;
var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;
//parsing text value to Float type for multipication
var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);
if (TotalWeight != TotalCustomWeight)
{
alert("pkg weight does not match total custom weight");
}
}
</script
and Off course you must need to validate for value to be number before calculation. This works perfect.