Can I recalculate a form field without a reload? - javascript

When a field in my form gets focus, I'd like a javascript function to be called that
calculates a value for that field without my putting in a specific button to do that.
Is this possible without causing the form to reload?
I have thought about making the Amount field read-only, and some other ways of doing this, but I'm looking to see if changing the Quantity field could cause the Amount field to change either using onchange in the Quantity field or onfocus in the Amount field.
Purchase Tickets<br>
<script type="text/javascript" language="JavaScript1.2">
<script type="text/javascript" language="JavaScript1.2">
document.write(
'<form name="InvGenPayTickets" action="'+PostURL+'"
onsubmit="return validateForm();" method=GET>');
</script>
<input type=hidden name="TplURL" value="GenPayCCInfo.html">
<input type=hidden name="CancelURL" value="Ooopsie.html">
<input type=hidden name="SuccessURL" value="Joanie.html">
<input type='hidden' name='TransDesc' id='TransDesc'
value="$_POST['TransDesc']; ?>" />
<input type='text' name='Quantity' id='Quantity' /> <br />
Amount<br />
$<input type='text' name='Amount' id='Amount' />
<input type="submit" value="Next">
<br>
</form>
Edit:
Here is the function that won't update. It is called if I use
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
but the Amount field does not update. I am not able to update using a calc button either.
<script type="text/javascript" language="JavaScript1.2">
function retTotalAmt()
{
alert("Got here.");
var total_amt
= (document.getElementById('Quantity').value * ticketCost)
+ DonationAmount;
document.getElementById('Amount').value = total_amt;
}
</script>
Per request in comments:
<input type='text' name='Quantity'
id='Quantity' onchange="return retTotalAmt();" />
Edit -- Show Problem
<script type="text/javascript" language="JavaScript1.2">
var ticketCost = 40.00;
function EnterPage()
{
var currentTotalAmount = DonationAmount + ticketCost;
//DonationAmount moved up to ticketCost's scope fixed problem.
var DonationAmount = <?php echo($_POST['DonationAmount']); ?>;
document.getElementById('DonationAmountField').value = DonationAmount.toFixed(2);
document.getElementById('Quantity').value=1;
document.getElementById('Amount').value = currentTotalAmount.toFixed(2);
return;
}

Without using jquery:
<input type='text' name='Amount' id='Amount' onfocus="amountOnFocus();" />
Javascript:
function amountOnFocus() {
amountField = document.getElementById('Amount');
//Do calculations
amountField.value = resultOfCalculations;
}
If you wanted, you could also put a change event listener on the Quantity input so it will calculate when the value of that textbox changes.
EDIT: This onchange event works for me:
Markup:
<input type="text" id="txtChangeMe" onchange="txtChangeMeOnChange();" />
Javascript:
<script type="text/javascript">
function txtChangeMeOnChange() {
alert('changed');
}
</script>

I'm not quite sure what additional information you need, as you seem to be aware of all the ingredients for making this happen: You know that you want to detect an event, you know that you need to call a function, so I'm hoping I haven't missed something about what you're asking. I'm going to assume that you just need to know how to tie all these parts together.
The simplest example might be:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').value = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<input type="text" id="Amount" value="100" />
though it's worth noting that this does not follow best-practices, which would involve binding an event listener separately.
On the off-chance that you accidentally typed "button" when you meant "field", I will also mention that you can update any other element's innner HTML with the ''innerHTML'' attribute, eg:
<input type="text" id="Quantity" value="10" onchange="document.getElementById('Amount').innerHTML = parseInt(document.getElementById('Quantity').value,10) * 10.0;" />
$<span id="Amount">100</span>
Of course, you can define the actual logic elsewhere, and just use ''onchange="yourFunction();"'' instead of putting everything inline, as well.
I know you mentioned "onchange" and "onfocus", though personally I tend to prefer "onkeyup", so that values will change as the user is typing.
Apologies if I've completely missed the point in your question.

Sure. Use something like this which will fire when quantity change:
$("#Quantity").change(function(){
// perform your calculations here
};
This requires the jQuery framework.

function calcPrice()
{
....
}
<input type='text' name='Quantity' id='Quantity' onchange='calcPrice();'/>
<input type='text' name='Amount' id='Amount' onfocus='calcPrice();'/>

Do you have access to jQuery? If not then you would have to bind an change event to your "quantity" input element to listen for a change of its input. Then you would simply need to modify the contents of the "amount" input.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
var el = document.getElementById("Amount");
el.addEventListener("change", changeAmount);
function changeAmount(){
var quantity = document.getElementById("Quantity");
quantity.value = "SET YOUR VALUE";
}

Try this solution
Html
<div class="form-group row">
<label for="inputQty" class="col-sm-4 col-form-label">Quantity</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" value="1" type="number" step="1" min="1" max="9999999" class="form-control" id="inputQty" required>
</div>
</div>
<div class="form-group row">
<label for="inputPrice" class="col-sm-4 col-form-label">Price</label>
<div class="col-sm-8">
<input onkeyup="CalculateItem();" onkeydown="CalculateItem();" onchange="CalculateItem();" onfocus="CalculateItem();" type="number" step="0.1" min="1" max="9999999" class="form-control" id="inputPrice" required>
</div>
</div>
<div class="form-group row">
<label for="inputPriceNoVat" class="col-sm-4 col-form-label">Price (no VAT)</label>
<div class="col-sm-8">
<input readonly type="text" class="form-control" id="inputPriceNoVat">
</div>
</div>
JS
<script type="text/javascript">
function CalculateItem()
{
try {
let inputPriceNoVat = $('#inputPrice').val() * $('#inputQty').val();
$('#inputPriceNoVat').val(inputPriceNoVat);
} catch (e) {
$('#inputPriceNoVat').val(0);
}
}
</script>

Related

How to limit the input based on the value of another input using javascript

Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
</div>
Hello, Can anyone help me with this problem. How to limit the input based on the value of another input using javascript .
For Example the Value of Balance Input is 200 so that the possible input in PaidBalance is within 0-200 only.
Sorry, I'm just a student. Thanks :):)
Something like this?
$("#paidbalance").keyup(()=>{
const balance = parseFloat($("#balance").val())
const paidBalance = parseFloat($("#paidbalance").val())
if( paidBalance > balance)
$("#paidbalance").val(balance)
else if(paidBalance < 0)
$("#paidbalance").val(0)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Paid Balance
</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" />
Balance
</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" readonly/>
This is with pure javascript without jquery. Also, note that the accepted answer doesn't work if user paste some value with mouse right-click: paste option.
function f1()
{
var max = Number(document.getElementById("balance").value);
var paid = document.getElementById("paidbalance");
var v = Number(paid.value);
//if(isNaN(v)) {...} //input is not a number
if(v>max) {
paid.focus(); //to keep focus on input
paid.value=max; //you may comment out this line to don't override value
}
}
<div class="col-md-2">
Paid Balance</strong>: <input type="text" name="paidbalance" id="paidbalance" class="form-control" oninput="f1()" />
</div>
<div class="col-md-2" >
Balance</strong>: <input type="text" name="balance" id="balance" class="form-control" value="200" />
</div>
You might wanna change the type to number in this case and add max property in input. If the value of balance Input is different every time. You might considering assign it to a variable and pass it to the max property
Paid Balance</strong>:
<input type="number" name="paidbalance" id="paidbalance" max="200" class="form-control" />
Change the input to type="number" and add jQuery like this:
var balance = $('#balance')
var paidBalance = $('#paidbalance')
paidBalance[0].setAttribute('max', balance.val())
Example:
https://jsfiddle.net/Daniel_Knights/t4hb0z7p/8/

Why is my checkbox on change not working (AJAX)

This is how my razor code looks like
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
$("#Attendance").on("change", function () {
$("#Grade").attr("disabled", this.checked);
});
</script>
Yet for some reason, clicking on the checkbox does nothing at all. I have tried this with simple script as well, and that didn't work either.
document.getElementById('Attendance').onchange = function () {
document.getElementById('Grade').disabled = this.checked;
};
Neither of these worked.
I have even copied some solutions from here (one of them is that last simple scrip with document.getElementbyId, and none of it worked. I have to be missing something simple, but I've been looking at this for the past hour and I still can't figure it out.
I apologize if the question is stupid or noob-level. But I am getting desperate.
EDIT: Simply to add more information, this form works perfectly fine when submitting data, controller saves the stuff to the database... Everything works fine, just not the part where it disables the ability to edit the Grade if the student has not attended.
So the objective, is to disable the input field when the checkbox for "attendance" is checked
The .attr() method only manage string; So if you want to change an attribut like disabled or even checked with a boolean or something else, you have to use the prop method.
For more information check this post :
.prop() vs .attr()
You can execute the snippet below.
$("#Attendance").on("change", function () {
$("#Grade").prop("disabled", this.checked)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form asp-action="Save" asp-controller="ClassesHeld" method="post">
<input asp-for="ClassHeldId" value="#Model.ClassHeldId" hidden />
<div class="form-group">
<label>Student</label>
<input asp-for="#Model.Student" value="#Model.Student" class="form-control" readonly />
</div>
<div class="form-group">
<label>Grade</label>
<input id="Grade"asp-for="Grade" type="number" value="#Model.Grade" class="form-control" min="0" max="5" />
</div>
<div class="form-group">
<label>Attendance</label>
<input id="Attendance" class="form-check-input" asp-for="Attendance" type="checkbox"/>
</div>
<button class="btn btn-primary" type="submit" value="Save">Save</button>
</form>
<script>
</script>
I think you actually need to remove the disabled attribute when you don't want it. Maybe try this:
$(document).ready(function() {
$("#Attendance").on("change", function () {
if (this.checked) {
$("#Grade").attr("disabled", true);
} else {
$("#Grade").removeAttr("disabled");
}
});
});

Can't get Jquery to write the output of a function to html

new guy here. I have a feeling this is an extremely basic question but I can't get this Jquery code to write the output of the function to html and have it show up. I believe it's an issue with the script but unsure if I am doing something wrong with html as well.
The goal of this function is to create a calculator that gives future investment value based on what the user inputs. When I click submit, It used to change all of the html to show just 'NaN' but now when I click the submit button, it clears the input boxes but does not give me any number or any answer even though I believe I've set it to display the number to
HTML
<body>
<div id = "futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>
jQuery
$('#submit').click(function(){
$('#result').html(function(){
return toString(output,10);
});
});
var princeple = parseInt($('#princeple'),10);
var time = parseInt($('#time'),10);
var rate = parseInt($('#rate'),10);
var output = (princeple * time + rate);
Here is your fix:
$('#submit').click(function(){
var princeple = parseInt($('#princeple').val());
var time = parseInt($('#time').val());
var rate = parseFloat($('#rate').val()/100);
var output = ((princeple * rate) * time);
$('#result').html(output);
//prevent from page reload
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>
You have to calculate the value inside the click event and assign to the result. The formula for calculating interest is also incorrect.
Try the following code, basically you need:
Calculate your variables inside cb click and than output the resut in your div #result. Use .val to get values for your inputs and event.preventDefault() to avoid form submit (which is the browser default behavior).
$('#submit').click(function(event) {
var princeple = parseInt($('#princeple').val(), 10);
var time = parseInt($('#time').val(), 10);
var rate = parseInt($('#rate').val(), 10);
var output = (princeple * time + rate);
$('#result').html(output);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="futurevalue">
<form>
<input type="radio" name="formula" value="future_investment" checked>Future Investment<br>
<label for="princeple">Enter the princeple amount invested:</label>
<input id="princeple" type="number" name="princeple" step="0.01"><br>
<label for="time">Enter how long the investment will be for (in years):</label>
<input id='time' type='number' name='time'><br>
<label for='rate'>Enter the expected interest rate:</label>
<input id='rate' type="number" name='rate'><br>
<input id='submit' type='submit' name='submit'>
</form>
<p>Total:</p>
<p id='result'></p>
</div>

Change $(this) input field color based on class effecting all classes in div

I have this HTML that occurs multiple times on a page:
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span></p>
</div>
<div class="col-r">
<div class="qty-days">
<input name="Mon" class="qty-input" value="0" maxlength="2" />
<input name="Tue" class="qty-input" value="0" maxlength="2" />
<input name="Wed" class="qty-input" value="0" maxlength="2" />
<input name="Thu" class="qty-input" value="0" maxlength="2" />
<input name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>
I have this JQuery to detect when the input field is changed and if the value is greater than 0, change the color to red.
$(".qty-input").change(function(){
var qty = parseInt($(this).val());
if(qty > 0){
$(this).css('color','red');
}
else{
$(this).css('color','black');
}
});
It is behaving very unpredictably. When I change the value of the first input field (Monday), it makes all 5 inputs red. Then sometimes it is changing the colors back to black in completely different rows sets of days. Seems like a simple problem to fix, but having trouble figuring it out.
The problem is that this code:
var qty = $(this).val();
Returns a string. And this code compares that string to a Number
if(qty > 0){
Try changing the first line of code to:
if ($(this).val()) {
var qty = parseInt($(this).val(), 10);
}
And it should start to work more consistently but you will also want to validate that the input is all numbers.
Thanks for all the responses. It prompted me to dig deeper at which point I discovered another piece of code in a different JS file that was trying (incorrectly!) to do the same thing. The code I have above is in fact sound and works perfectly. I apologize for wasting anyone's time here. I didn't realize that my client had a developer who had already attempted to do this (and who also put the code in the wrong file).
Use change event target to get to the element
$(document).ready(function() {
$(".qty-input").change(function(e) {
var target = e.target;
var qty = $(target).val();
if (qty > 0) {
$(target).css('color', 'red');
} else {
$(target).css('color', 'black');
}
alert("value is " + qty)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="canteen-item">
<div class="col-l">
<h4>Chicken Sandwich</h4>
<p>$<span class="canteen-price">3.50</span>
</p>
</div>
<div class="col-r">
<div class="qty-days">
<input type="text" name="Mon" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Tue" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Wed" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Thu" class="qty-input" value="0" maxlength="2" />
<input type="text" name="Fri" class="qty-input" value="0" maxlength="2" />
</div>
</div>
</div>

Trouble filling Multiple Textbox values from other Textboxes when Checkbox is Clicked

I DID search but couldn't find anything that helped me to figure out my particular issue. I've got textboxes for a customer address, and textboxes for a business address, and a checkbox to mark if the address should be the same. I need to get the Checkbox to fill the business address with the customer address onclick and unfill them on onclick. I've tried using a few different ways with jquery and straight javascript DOM manipulation, the most success I've had is in the following code, it only fills the biz_street textbox with the cust_street value though, and I don't understand why. Some help would be greatly appreciated, either in jquery or straight javascript, can't use php (sadly).
Here it is on jsfiddle (as suggested by rjmunro, good idea :) ): http://jsfiddle.net/yN73w/1/ not working at all
Here is the jquery:
$("#same_box").click(function () {
var v = $("#cust_street").val();
var x = $("#cust_city").val();
var y = $("#cust_state").val();
var z = $("#cust_zip").val();
$("#biz_street").val(v);
$("#biz_city").val(x);
$("#biz_state").val(y);
$("#biz_zip").val(z);
});
Or more simply:
$("#same_box").click(function () {
$("#biz_street").val($("#cust_street").val());
$("#biz_city").val($("#cust_city").val());
$("#biz_state").val($("#cust_state").val());
$("#biz_zip").val($("#cust_zip").val());
});
And the HTML:
<label id="cus_street_label">Street</label></br>
<input type="text" name="cust_street" id="cust_street" style="width:90%" /></br>
<div id="cus_city">
<label id="cus_city_label">City</label></br>
<input type="text" name="cust_city" id="cust_city" style="width:100%" /></br>
</div>
<div id="cus_state">
<label id="cus_state_label">State</label></br>
<input type="text" name="cust_state" id="cust_state" style="width:70%" /></br>
</div>
<div id="cus_zip">
<label id="cus_zip_label">Zip</label></br>
<input type="text" name="cust_zip" id="cust_zip" style="width:65%" /></br>
</div>
<input type="checkbox" name="same_box" id="same_box" >Address Same as Customer</input></br>
<label id="biz_street_label">Street</label></br>
<input type="text" name="biz_street" id="biz_street" style="width:90%" /></br>
<div id="biz_city">
<label id="biz_city_label">City</label></br>
<input type="text" name="biz_city_box" id="biz_city_box" style="width:100%" /></br>
</div>
<div id="biz_state">
<label id="biz_state_label">State</label></br>
<input type="text" name="biz_state_box" id="biz_state_box" style="width:70%" /></br>
</div>
<div id="biz_zip">
<label id="biz_zip_label">Zip</label></br>
<input type="text" name="biz_zip_box" id="biz_zip_box" style="width:80%" /></br>
</div>
Thank you very much for any help, and I apologize if I missed a topic like this in my searching.
(Also, unrelated, but why doesn't function formReset() {
document.getElementById("customer").reset();
} work in firefox? It only seems to work in chrome)
(you need to select jQuery in your JSFiddle, like http://jsfiddle.net/7HGNx/)
Your code is referring to biz_city but the element's id is biz_cty_box.
You probably don't want to attach to click, you probably want listen to the change event, as this will fire when the option is changed without the mouse. I would also check that the change has been ticking the box, not unticking the box.
$("#same_box").change(function (e) {
if ($(this).is(":checked")) {
.
.
.
}
}

Categories

Resources