jquery: how to update input value using onchange? - javascript

I created a discount function for my order page where I have an issue that is , on my order page by default when product quantity is 1 then discounted rate show correctly in Final textbox but when I change the Quantity, like 1 to 2,3,4,5.. then my code not works and the amount show without discount rate.
I try to fix this but I not understand where is mistake and how I fix that.
Below is my code which I am using please help and tell me how I make this correct.
Your help will be really appreciate.
Thank you!
function getTotal(row = null) {
if(row) {
var disc = $('#dis_1').val();//
var dec = (disc/100).toFixed(2); //
var total = Number($("#rate_value_"+row).val()) * Number($("#qty_"+row).val()) * dec;
//total = total.toFixed(2);
var rate = Number($("#rate_value_"+row))-total;
total = total.toFixed(2);
$("#amount_"+row).val(total);
$("#amount_value_"+row).val(total);
subAmount();
} else {
alert('no row !! please refresh the page');
}
}
//**---**/
//*---*//
// get the product information from the server
function getProductData(row_id)
{
var product_id = $("#product_"+row_id).val();
if(product_id == "") {
$("#rate_"+row_id).val("");
$("#rate_value_"+row_id).val("");
$("#qty_"+row_id).val("");
$("#amount_"+row_id).val("");
$("#amount_value_"+row_id).val("");
} else {
$.ajax({
url: base_url + 'orders/getProductValueById',
type: 'post',
data: {product_id : product_id},
dataType: 'json',
success:function(response) {
// setting the rate value into the rate input field
$("#rate_"+row_id).val(response.price);
$("#rate_value_"+row_id).val(response.price);
$("#dis_"+row_id).val(response.discount);
$("#dis_value_"+row_id).val(response.discount);
$("#qty_"+row_id).val(1);
$("#qty_value_"+row_id).val(1);
//DISCOUNT
var disc = $('#dis_1').val();
var dec = (disc/100).toFixed(2);
var total = Number(response.price) * dec;
var rate = Number(response.price)-total;
total = rate.toFixed(2);
$("#amount_"+row_id).val(total);
$("#amount_value_"+row_id).val(total);
subAmount();
} // /success
}); // /ajax function to fetch the product data
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
<td>
<input type="text" name="rate[]" id="rate_1" class="form-control" autocomplete="off" placeholder="Rate">
</td>
<td>
<input type="text" placeholder="Discount" name="dis[]" id="dis_1" class="form-control" autocomplete="off">
</td>
<td>
<input type="text" placeholder="Total Price" name="amount[]" id="amount_1" class="form-control" autocomplete="off">
</td>
I am using my database to fetch the amount like product real rate, discounts.

In your line of HTML
<td><input type="text" name="qty[]" id="qty_1" class="form-control" required onkeyup="getTotal(1)" placeholder="Quantity"></td>
you are always calling getTotal with a value of 1, I think you want to instead get the value of the text box when the getTotal function is called and use that as your row value. In jquery you can get the value of the box by
row = $("#qty").val()

Related

Find sum of automatically generated input fields value

I have a button that when you click it appends an input fields in a div,
this values comes from ajax request.
var i = 0;
$(document).on('click', '#add-btn', function() {
++i;
var user = $('#productName').attr('value');
var price = $('#price').attr('value');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getPrice.php",
data: {user:user, price:price},
dataType: "html", //expect html to be returned
success: function(response){
$("#dynamicAddRemove").append('<tr style="height:5em;" id="tr"><td><input name="productName['+i+']" readonly class="form-control" type="text" value="'+user+'"/></td><td><div class="quantit buttons_added"><input class="form-control quantity" id="number" type="number" name="qty[' + i + ']" value="1"/></div></td><td><input class="form-control amount" type="text" readonly value="'+price+'" name="price[' +i +']"/></td><td class="td"><input type="text" value="'+price+'" name="subTotal['+i+']" placeholder="Subtotal" class="form-control subtotal" id="grandTotal" readonly/><td><button type="button" name="add" class="btn btn-danger remove-tr">-</button></td>');
}
});
});
after appending the input fields now i want to add every value of the subTotal to get grandTotal.
var iSum = 0;
$(document).on('mouseout', '.amount , .quantity, #addvalue', function() {
iSum = 0;
$('input[name="subTotal[]"]').each(function(){
var LiSum =parseInt($('input[name="subTotal[]"]').val());
if(LiSum != undefined || LiSum != ''){
iSum+=LiSum;
}
});
$('#sum').html(iSum);
alert(iSum);
});
after successfully appending values, i keep on getting 0 as grandTotal
Replace $('input[name="subTotal[]"]') by $('input[name^="subTotal"]'). This will find all input fields with names starting with "subTotal". The name "subTotal[]" you were originally looking for does not appear anywhere in your markup.

Calculating price from quantity

I making the shops for my site, and but I can't understand why this conde don't wont to work...Here's the code:
<script>
function Price() {
var Quantity = document.getElementsByClassName('BUY')[0].value;
var Total = Quantity * 20;
if (!IsNan(Total)) {
document.getElementsByClassName('Total').innerHTML = Total;
document.getElementsByClassName('Quantity').innerHTML = Quantity;
} else {
document.getElementsByClassName('Total').innerHTML = "Invalid number";
document.getElementsByClassName('Quantity').innerHTML = 0
}
}
Here is the html:
<input style="margin-top:1%;" type="text" name="BUY" class="input" maxlength="1000" autocomplete="on" placeholder="Buy " onchange="Price()" required>Price for <span class="Quantity">0</span>Views:<span class="Total">0</span> Satoshis<br>
From this code I expect a print of the calculation based on the quantity but the code don't work and I get no errors...
document.getElementsByClassName('BUY') will search for elements having class 'BUY', but ur input has class 'input'
you have worng class name in the script that's why it is not working.
corrected code:(Just copy & paste it .works changed class into ID)
Because using classname it is not fetching the correct value instead it assigns Quantity as undefined refer this answer
function price(){
var Quantity=document.getElementById('buy').value;
var Total=Quantity*20;
if(Total != 'NaN'){
document.getElementById('Total').innerHTML=Total;
document.getElementById('Quantity').innerHTML=Quantity;
}else{
document.getElementById('Total').innerHTML="Invalid number";
document.getElementById('Quantity').innerHTML=0;
}
}
<input style="margin-top:1%;" type="text" name="BY" id="buy" maxlength="1000" autocomplete="on" placeholder="Buy " onkeyup="price()" required/>Price for
<span id="Quantity">0</span>
Views:<span id="Total">0</span>
Satoshis<br>

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.

Grab form fields and calculate based on inputs

I'm getting an undefined error and don't know why this isn't working.
It's supposed to divide the rent by the amount of roommates:
function splitRent() {
var roommates = document.getElementById("rent");
var rent = document.getElementById("rent");
var rentEach = rent / roommates;
if (document.getElementById("submit") == true) {
document.write("You each should pay" + " " + rentEach)
} else {
document.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
You want to take the value of the fields, not the fields themselves.
document.getElementById() returns the node, but you want the value of the input field:
var rent = document.getElementById("rent").value;
Also, you're getting the value of the rent twice; you want to check the roommates as well.
var roommates = document.getElementById("roommates").value;
Lastly, document.getElementById("submit") == true doesn't mean anything: you're comparing a button node with a boolean value, which doesn't make sense. If you want to check to make sure that both fields are filled, try this:
if(roommates && rent){
//do calculations
}else{
window.alert("Enter something"); //note that it's window.alert(), not document.alert(), which is not a function
As it stands, this allows people to enter things that are not numbers; there are two things that you could do to fix that.
Use parseInt()/parseFloat() to ensure that you're extracting a number
Check that you actually have a number before doing calculations
You'd do something like this:
var rent = parseInt(document.getElementById("rent").value);
var roommates = parseFloat(document.getElementById("rooommates").value);
If you use the checking I've done above (rent && roommates), the validation will take place there (it checks for both empty and NaN values).
function splitRent() {
var roommates = parseInt(document.getElementById("roommates").value);
var rent = parseFloat(document.getElementById("rent").value);
var rentEach = rent / roommates;
if (roommates && rent) {
document.write("You each should pay" + " " + rentEach)
} else {
window.alert("Gimme info")
}
};
<h1>Roommate Room Splitter</h1>
<form id="myForm">
Roommates:
<input type="text" name="roommates" id="roommates">
<br/>Rent:
<input type="text" name="rent" id="rent">
<br/>
<input type='submit' id='submit' value='Submit' onclick="splitRent()" />
</form>
Shouldn't this be:
var roommates = document.getElementById("roommates").value;
var rent = document.getElementById("rent").value;
Do you always get "1" for your result?

Fields calculating only after a refresh

I apologize in advance for what I assume is a very basic question, but I am very new to scripting and would like to ask for some advice on a problem I am having.
Essentially I am creating a website that should sum the dollar amounts of two fields based on hours worked and return a total dollar amount. One of the fields has a fixed dollar amount and the other is a variable.
As far as I can tell the code should be working, but the field that should be user generated (esceptionalRate) seems to calculate correctly only after a page refresh, and then only on firefox... instead of automatically updating the total value when a change is made to the user field
code as follows:
<head>
</head>
<body>
<script>
$(document).ready(function () {
var standardRate = 110;
var exceptionalRate = $("#ex_rate").val();
var standardEntry = 0;
var exceptionalEntry = 0;
var totalVal = 0;
$("#Standard").on("change",function(){
standardEntry = $(this).val() * standardRate;
totalVal = standardEntry + exceptionalEntry;
$("#Amount").val(totalVal);
});
$("#Exceptional").on("change",function(){
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});
</script>
and here's the HTML side:
<input name="Standard" type="number" step="any" value="0" id="Standard" size="10" />
<input type="text" size="10" name="ex_rate" id="ex_rate" />
<input name="Exceptional" type="number" step="any" value="0" id="Exceptional" size="10" />
<td valign="top" nowrap="nowrap"><font size="2">Total Amount Requested </font></td>
<td><input name="Amount" type="text" id="Amount" size="35"/></td>
thanks in advance for all your wisdom and knowledge.
You have forgotten to close the $(document).ready function
Try:
$(document).on("change", "#Standard", function(){
And:
$(document).on("change", "#Exceptional", function(){
The problem is that your exceptionalRate variable is out of the scope of your calculation, and only gets set to the initial value upon the page loading. You need to move it within the change handler:
$("#Exceptional").on("change",function(){
exceptionalRate = $("#ex_rate").val();
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});

Categories

Resources