I'm doing an assignment for a uni subject and having some trouble with javascript. I want to be able to change the value of an input field based on the value of another field. in short, the purpose is to input a quantity of a product in one field, and have the field next to it change to display the total amount of money required to purchase that quantity of products.
When I run my html, the quantity entered does not change the value of the cost field and im thinking there must be something wrong with my javascript.
Here is a copy of my javascript function, and the related html for it to execute within.
SCRIPT:
function calcRowWash(){
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
var quantity = 0;
if(x.value!=""){
quantity = parseInt(x.value);
}
var totalC = (quantity*0.30);
document.getElementById("totc").value = totalC;
return;
}
HTML:
<td width = "90px" align ="left"><input type = "text" id ="quantc" name = "quantWash" size = "5" tabindex = "13" onblur="calcRowWash()"/></td>
<td width = "90px" align ="left"><input type = "hidden" id ="totc" name = "washtotal" size = "5" tabindex = "14" value=""/></td>
Thanks for the help!.
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
This is redundant. IDs are unique on the entire document, so this will suffice:
var x = document.getElementById('quantc');
Also note that I removed the .value - this was the problem, because you then tried to get the value... of the value.
This works.
calcRowWash = (function(){
var x = document.getElementById("quantc");
var quantity = 0;
if (x.value!="") quantity = parseInt(x.value);
var totalC = (quantity*0.30);
document.getElementById("totc").value = totalC;
});
JSFiddle.
try with this code
function calcRowWash() {
var x = document.forms[0]['quantc'].value;
var quantity = 0;
if (x != "") {
quantity = parseInt(x);
}
var totalC = (quantity * 0.30);
document.forms[0]['totc'].value = totalC.toString();
}
Html Markup, I've changed the hidden type for an textbox and It works for me.
<td width = "90px" align ="left"><input type = "text" id ="quantc" tabindex = "13" onblur="calcRowWash()"/></td>
<td width = "90px" align ="left"><input type = "text" id ="totc" tabindex = "13"/></td> </div>
function calcRowWash(){
var theForm = document.forms["orderform"];
var x = theForm.getElementById("quantc").value;
var quantity = 0;
// Check if it is not empty
if(x.value != ""){
// Check if it is a valid number
if(x / x == 1){
quantity = parseInt(x.value);
}
}
var totalC = (quantity * 0.30);
document.getElementById("totc").value = totalC;
}
this works for me.
<form name="myForm" action="#" method="POST">
<input type = "text" id="quantc" name = "quantWash" size = "5" tabindex = "13" onblur="calcRowWash()"/>
<input type = "hidden" id ="totc" name = "washtotal" size = "5" tabindex = "14" value=""/>
</form>
function calcRowWash(){
var quantity = document.myForm.quantWash.value;
var price = 10.0;
document.myForm.washtotal.value = quantity * price;
}
The function doesn't comprise the parsing stuff. I just want to show how to read and set the value of both input fields.
You can use this JavaScript Code:
var inp = document.getElementById("inp"); // getting the Input ID
function change_value() {
inp.value = 'Your Value'; // <-- value
}
You can add Events:
inp.onfocus = change_value;
inp.onblur = another function with another action;
Good Luck Liam and Have a Nice Day.
Related
I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}
I have a variable that gets its value once an ID is clicked, via .innerText
var currentID = e.target.id;
I need the value of this variable, currentID, to be stored in a new variable which is named just like the ID of which it got its value.
So, if a user clicks an element with the ID price1, and the price is 200.
A new variable with the name price1 with value 200 should be created.
Then, I want to sum up the new variables: price1+price2+price3 etc = totalprice.
This is what I'm doing right now:
$('div.unselected-option').click(function(e) {
$(this).toggleClass("selected-option unselected-option")
if ($(this).hasClass("selected-option")) {
var currentID = e.target.id;
console.log(currentID);
var price1 = document.getElementById(currentID).innerText
var finalprice
finalprice = +price1;
document.getElementById("showprice2").innerHTML = finalprice
Here's an image of the design:
I can't seem to figure this out... What I'm doing right now just results in having 1 variable which means I cannot sum anything up... I would love your view on this issue!
Your use case is pretty strange I hope your backend is secured and well made.
Here is a potential solution:
<div id="a1" onclick="handleProductClick">20</div>
<div id="a2" onclick="handleProductClick">40</div>
<div id="b1" onclick="handleProductClick">20</div>
<div id="b2" onclick="handleProductClick">60</div>
...
<div id="total-price">0</div>
...
const basket = {}
function addToBasket(event) {
const { id, innerText } = event.target
const price = parseInt(innertText, 10)
const product = basket[id]
const count = product.count || 1
basket[id] = {
price,
count
}
}
function getBasketTotalPrice = () => {
return Object.keys(basket)
.reduce((total, product) => total + product.count * product.price, 0)
}
function handleProductClick = (event) => {
addToBasket(event)
const totalPrice = getBasketTotalPrice()
document.querySelector('#total-price').innerHTML = totalPrice
}
My code generates a two dimensional matrix when the OK is clicked. The code stores the data in the multidimensional array, but I am trying to add a sort function to the code which rearranges the code in ascending order using the 4th text box. Any suggestions on how I can do that ?
HTML Code
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<input type = "text" size = "1" id = "text1"/>
<input type = "text" size = "1" id = "text2"/>
<input type = "text" size = "1" id = "text3"/>
<input type = "text" size = "1" id = "text4"/><br>
<input type = "button" value = "Ok" id = "operation" onClick = "display()"/>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut" onClick = "sort()"><br><br>
<div id="expressions">
</div>
</div>
</div>
Javascript Code
function display()
{
var arrayOne =[document.getElementById('text1').value,document.getElementById('text2').value,document.getElementById('text3').value,document.getElementById('text4').value ];
new_array=arrayOne.join(" ");
var para = document.createElement("p");
var t = document.createTextNode(new_array);
para.appendChild(t)
document.getElementById("expressions").appendChild(para);
}
function sort(){
var dispArr = [document.getElementById('text1').value,
document.getElementById('text2').value, document.getElementById('text3').value,document.getElementById('text4').value];
var myArray = [];
for(var i = 0 ; i < 1 ; i ++ ) {
myArray[i] = [];
for(var j = 0 ; j < 5 ; j++ )
{
myArray[i][j] = dispArr[j];
console.log(myArray[i][j]);
}
}
}
You would better keep the whole matrix in a memory variable, and add to that. Also consider that when the output is sorted, you must know how to get back to the original order also, so that the "As Entered" button still has the desired effect. So, it is better to have a display function that starts from scratch, empties the output and reproduces all the data in either entered or sorted order.
Here is how you could do that:
var matrix = []; // global value with all data
function addExpression() {
var arrayOne = [
document.getElementById('text1').value,
document.getElementById('text2').value,
document.getElementById('text3').value,
document.getElementById('text4').value
];
// add to matrix
matrix.push(arrayOne);
display(false);
}
function display(byResult) {
// Determine whether to sort or not:
var matrix2 = byResult ? sorted(matrix) : matrix;
// display each row:
var expressions = document.getElementById("expressions");
expressions.innerHTML = ''; // empty completely
matrix2.forEach( row => {
var para = document.createElement("p");
var t = document.createTextNode(row.join(" "));
para.appendChild(t)
expressions.appendChild(para);
});
}
function sorted(m){ // Create a copy, and sort that by last column
return m.slice().sort( (a, b) => a[3] - b[3] );
}
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<input type = "text" size = "1" id = "text1"/>
<input type = "text" size = "1" id = "text2"/>
<input type = "text" size = "1" id = "text3"/>
<input type = "text" size = "1" id = "text4"/><br>
<input type = "button" value = "Ok" id = "operation" onClick = "addExpression()"/>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut" onClick="display(false)">
<input type = "button" value = "By Result" id = "resultBut" onClick = "display(true)"><br><br>
<div id="expressions">
</div>
</div>
</div>
</div>
<?php
$ctr = 0;
while($ctr <= 10){
?>
<td><input required type='text' name='amount[<?echo $ctr; ?>]' class='amount'></td>
<td><input required type='text' name='mode[<?echo $ctr; ?>]' value='Cash'></td>
<?php
$ctr++;
}
?>
Total Amount: <span class="total_amount">0.00</span>
Total Cash : <span class="total_cash">0.00</span>
Total Check: <span class="total_check">0.00</span>
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
$('.amount').each(function () {
total += parseFloat($(this).val());
});
$('.total_amount').html(total);
});
Using the code above, I can get the total amount of the number I encode in the input amount fields. How can I get the total per mode, cash(default) and check (user can change mode to check)?
If you sure, that next input width mode always corresponds, you can use JQuery.next. So it is necessary to check the value of each parameter to NaN.
$(document).on('blur','.amount',function () {
var total = 0;
var total_cash = 0;
var total_check = 0;
var val, mode;
$('.amount').each(function () {
val = parseFloat($(this).val());
val = val ? val : 0;
total += val;
mode = $(this).next().val();
switch(mode) {
case "Check" : total_check += val; break;
case "Cash" : total_cash += val; break;
}
});
$('.total_amount').html(total);
$('.total_cash').html(total_cash);
$('.total_check').html(total_check);
});
http://jsfiddle.net/ag0a78jd/
The following only works if your indexes are consistent (eg. every amount[x] has a mode[x]):
var total = {};
$('.amount').each(function(idx)
{
var mode = $('[name="mode['+idx+']"');
if (!total[mode.val()])
total[mode.val()] = 0;
total[mode.val()] += parseFloat($(this).val());
}
);
console.log(total);
jsFiddle
Use jquery to get the index of the current element in the set of "amount" elements.
var index = $( ".amount" ).index( this );
Get the corresponding Cash/Check element value with the index you got just above
var mode_value = $("input[name='mode["+index+"]']").val();
Then check that value and store the value in the right variable
if (mode_value == "Cash")
total_cash = total_cash + $(this).val();
if (mode_value == "Check")
total_check = total_check + $(this).val();
The whole code must be inside the blur event.
Why do I get only zero in my calculation?
Code:
<?php echo 'AU$ <input type="text" name="pay_total" class="amount_text_change" id="amount_textbox_'.$i.'" onChange="UpdateValue_'.$i.'()" onKeyUp="AddInputs()" value="1">'; ?>
<td>Total</td>
<td>AU$ <span id="Display"></span></td>
Javascript:
function AddInputs()
{
var total = 0;
//var coll = document.getElementsByTagName("input")
var coll = document.getElementsByTagName("pay_total")
for ( var i = 0; i<coll.length; i++)
{
var ele = coll[i];
total += parseInt(ele.value);
}
var Display = document.getElementById("Display");
Display.innerHTML = total;
}
This javascript will auto add everytime user enter a numeric value in the textbox, but it's strange, the result is zero, must be something missing, can you help me?
Thanks
This...
document.getElementsByTagName("pay_total")
should be...
document.getElementsByName("pay_total")