With the following script, i am trying to validate whether the refund amount wlt_ln_refund_amt is greater than the balance amount wlt_ln_bal using keyup function.
In my html read only field wlt_ln_bal (field type = number) i have a an amount 222.00
the other field wlt_ln_refund_amt (field type = number)
The testcase
for the value 3 the system is throwing an error message like "Refund amount Rs.3 is greater than Balance Rs.222.
for the values 1, 2 or 2000 the system is not throwing any errors
Here is my html code:
<form id="lnrefund" name="lnrefund"
method="post" role="form"
class="form-horizontal"
action="<?php echo $_SERVER['PHP_SELF']; ?>"
onsubmit="return (checkform() && confirm_update())">
<div class="form-group">
<label class="col-md-2 col-xs-12 control-label">Loan Balance</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_bal" Name="wlt_ln_bal"
type="number"value ="<?php echo $bal ?>"
class="form-control required" readonly/>
<span class="help-block">Required</span>
</div>
</div>
<label class="col-md-2 col-xs-12 control-label">Refund Amount</label>
<div class="col-md-3 col-xs-12">
<input id="wlt_ln_refund_amt"
Name="wlt_ln_refund_amt"type="number" step="0.01"
class="form-control" required/>
<span class="help-block">Required</span>
</div>
</form>
And this is the javascript
<script type="text/javascript">
$(function(){
$("#wlt_ln_refund_amt").keyup(function () {
var ref = document.lnrefund.wlt_ln_refund_amt.value;
var bal = document.lnrefund.wlt_ln_bal.value;
if (ref>bal)
{
alert('Refund amount Rs.'+ref+ '\nis greater than Available Balance Rs.'+bal)
return true;
}
});
});
</script>
It looks like the variables are being compared as strings (i.e. alphabetically) you should try something like
var ref = parseInt(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseInt(document.lnrefund.wlt_ln_bal.value);
or maybe
var ref = parseFloat(document.lnrefund.wlt_ln_refund_amt.value);
var bal = parseFloat(document.lnrefund.wlt_ln_bal.value);
if you're expectiong decimals
Since you asked for suggestions... :P
I'd use jQuery to get the values of the two inputs. You're already using jQuery for the document ready function, so why not use:
var $refund = $('#wlt_ln_refund_amt'),
$balance = $('#wlt_ln_bal.value');
What you're doing works fine - as long as the structure of your HTML never changes. Using jQuery like this means you don't have to worry about ever wrapping your inputs in a containing DIV or changing the form to a popup dialog later on.
Next, I wouldn't use the keyup event, I'd use the blur event. Perhaps your use case requires the check after every keystroke, but that usually annoys users. If you bind to the blur instead of the keyup, your user will have an opportunity to correct a mistake during typing before getting yelled at by your function.
$refund.on('blur', function(){
var refAmount = parseInt($refund.val()),
balAmount = $balance.val() * 1;
if (refAmount > balAmount)
{
alert('Refund amount Rs.' +
refAmount +
'\nis greater than Available Balance Rs.' +
balAmount);
$refund.focus();
}
});
As someone else suggested, make sure the values you're comparing are numeric. You can use the parseInt as suggested (the preferred way) or force type conversion by multiplying the value by 1. Either way will result in a NaN (not a number) if the user enters something other than numbers.
After the alert, I'd return focus back to the refund amount to give the user another shot at the entry.
As a final suggestion, I'd recommend using readable variable names. Perhaps you shortened them just for this question, but descriptive variable names are much easier to deal with than obscure abbreviations.
Good luck!
Related
I’m looking for a way to automate a form.
Here are the details:
Extract a certain number (displayed in its html)
Do some calculations on the extracted number (percentage of that number)
Then automatically fill the remaining input fields with the result instead of typing it out.
This is a common occurrence in forms. The solution depends on what framework / libraries you're using. Assuming you're using none, here is how you might go about it:
https://jsfiddle.net/f52h1smj/1/
rough HTML:
<form>
<label for="number">Number: </label>
<input id="number" type="number" />
<br /> <br />
<label for="calculatedNumber">Calculated Number (50%): </label>
<input id="calculatedNumber" type="number" disabled="true" />
</form>
JS:
(() => {
//get the form element nodes
const $number = document.getElementById("number");
const $calculatedNumber = document.getElementById("calculatedNumber");
//add an event listen to the value you're going to use to pre calculate the other fields
$number.addEventListener("keyup", (e) => {
//it's value is available like so
const value = e.target.value;
//do some validation so that you're calculations don't throw exceptions
if (Number(value) !== 0 && !Number.isNaN(value)) {
//set the value of the other inputs to whatever you like by setting the 'value' property of the node.
$calculatedNumber.value = value / 2;
} else {
$calculatedNumber.value = null;
}
});
})();
These things become a lot simpler in frameworks like React and Angular.
I try to achieve Total of two input fields and those fields got their value dynamically from database after selecting a dropdown option. The html code and the sql query looks like below:
<select name="getData" ID="getData" onchange="getData()">
<option value="Select">Select Subscription Package</option>
<?php
$sql = "SELECT * FROM package WHERE status = 1";
$result = $connect->query($sql);
while($row = mysqli_fetch_row($result)){
echo '<option data-price="'.$row[4].'" value='.$row[0].'> '.$row[1].' </option>';
}
?>
</select>
<input type="text" id="price1" name="price1"/>
<input type="text" id="price2" name="price2"/>
<input type="text" id="totalAmount" name="totalAmount" onblur="totalCalc()">
Value of price1 & price2 changes when SELECT Option changed. Now I need to get total of these two fields by javascript. The js code is below:
<script>
function totalCalc() {
var A = document.getElementById("price1").value;
var B = document.getElementById("price2").value;
var C = A + B;
document.getElementById("totalAmount").value = C;
}
</script>
I got the total but it needs to click the total amount field. I want the calculation should be done automatically right after the first two fields got their values dynamically.
Any help is appreciated.
You should just set up change event handlers on both inputs that point to your totalCalc function and then, at the end of your getData() function, manually trigger the change event of one of the inputs.
If the code in getData is asynchronous, then the code that manually triggers the change event should be included in the success handler of the operation.
A note about the UI. If the two price fields are being auto-populated and users won't be inputting anything into them manually, disabling the fields is probably appropriate. With regards to the final total, an input there may not make sense at all - you just need to show the result, so a span element would work.
Also, inline HTML event attributes (onclick, onchange, etc.) should not be used. There are many reasons why this 20+ year old technique needs to die the death it deserves, but because so many people don't take the time to really learn JavaScript and modern best-practices, they just copy someone else's code that uses them and go on their merry way.
So, in the code below, I'm showing how to solve this problem using modern, standards-based code that follows best-practices.
// Get references to the DOM elements you'll need to work with
let a = document.getElementById("price1");
let b = document.getElementById("price2");
let total = document.getElementById("totalAmount");
let select = document.getElementById("getData");
let price1 = document.getElementById("price1");
let price2 = document.getElementById("price2");
// Set up event handlers in JavaScript, not HTML
select.addEventListener("change", getData);
price1.addEventListener("change", totalCalc);
price2.addEventListener("change", totalCalc);
function totalCalc() {
total.textContent = +a.value + +b.value;
}
function getData(){
// This is just mean to replicate what SQL does
price1.value = 15;
price2.value = 27;
// Manually trigger the change event for either one of the inputs
// If the existing code in getData is asynchronous, then this code
// should be added to the "success" callback. If not, it can just be
// placed at the end of the function as I'm showing it here.
var event = new Event('change');
price1.dispatchEvent(event);
}
<select name="getData" id="getData">
<option value="Select">Select Subscription Package</option>
<option>Data 1 from SQL</option>
<option>Data 2 from SQL</option>
<option>Data 3 from SQL</option>
</select>
<input type="text" id="price1" name="price1" disabled>
<input type="text" id="price2" name="price2" disabled>
<!-- No need to place the result in an <input> since users won't
be inputted data here. You just need to show it. -->
<span id="totalAmount"></span>
I am trying to populate a total field with id- #appointment-total_amount using javascript/jquery. Referring this Jsfiddle add two fields together - Which is working fine.
I am using this code in my _form.php
<?php
$script = <<<EOD
$(function() {
$('#appointment-doctor_fee').keyup(function() {
updateTotal();
});
$('#appointment-discount').keyup(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('#appointment-doctor_fee').val());
var input2 = parseInt($('#appointment-discount').val());
$('#appointment-total_amount').text(input1 + input2);
};
});
EOD;
$this->registerJs($script);
?>
But nothing is happening on the page.
I am not able to see what I am missing here.
Thanks.
Related HTML
<div class="form-group field-appointment-doctor_fee">
<label class="control-label" for="appointment-doctor_fee">Doctor Fee</label>
<input type="text" id="appointment-doctor_fee" class="form-control" name="Appointment[doctor_fee]" maxlength="10">
</div>
<div class="form-group field-appointment-discount">
<label class="control-label" for="appointment-discount">Discount</label>
<input type="text" id="appointment-discount" class="form-control" name="Appointment[discount]" maxlength="10">
<div class="form-group field-appointment-total_amount">
<label class="control-label" for="appointment-total_amount">Total Amount</label>
<input type="text" id="appointment-total_amount" class="form-control" name="Appointment[total_amount]" maxlength="10">
The error is in this line:
$('#appointment-total_amount').text(input1 + input2);
Should be:
$('#appointment-total_amount').val(input1 + input2);
Besides that add at least simple check for illegal numbers, because you will get NaN if one of the fields is empty or input value is not valid number. Some range limit will be good too.
var updateTotal = function () {
var doctorFee = parseInt($('#appointment-doctor_fee').val());
var discount = parseInt($('#appointment-discount').val());
var totalAmount = doctorFee + discount;
if (isNaN(totalAmount) || totalAmount < 0 || totalAmount > 100000) {
totalAmount = '';
}
$('#appointment-total_amount').val(totalAmount);
};
One more error is in script registration. Change to this:
use yii\web\View;
$this->registerJs($script, View::POS_END);
Otherwise it will be inserted before jQuery (and your script depends on it) and will not be working.
Registering scripts that way is not good practice, it's even mentioned in official documentation. Separate file and using assets is definitely better than struggling with dependencies and inserting js as string (the errors are hard to detect, no autocomplete, etc.).
http://jsfiddle.net/beY6d/
I want to make a simple HTML+JS page that basically gives the user 4 text fields to write the name of some product and an extra field that displays the remaining credit in the 5th text field.
<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>
var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;
There must be a .onblur (or .onfocus) event to make the "credit" field display 100 minus the sum of every other item.
Also, the price of the item must change depending on the color/type of item. Something like:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
If you do typeof remainingDosh.value, you'll see that it logs string. This means you'll have to convert the string to a number if you don't want to risk having NaN show up on your page.
Convert it with parseInt() like so:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
The second parameter, 10 is the radix, which in this case is decimal (though it defaults to decimal if left out I believe).
And the issue in question, as pointed out, is you're trying to do math on the element remainingDosh instead of using it's value.
Oh, and protip: instead of shirt.value, you can use this.value since the event comes from said element.
you're using remainingDosh instead of remainingDosh.value when you do your subtraction.
I have the following function:
function updateInput(ish){
document.getElementById("BetAmount").value = ish;
}
I have the following HTML inputs:
<input class="defaultText" type="number" name="BetAmount" id="BetAmount" onchange="updateInput(this.value)">
<input type="number" name="PotentialGain" id="PotentialGain" />
When users enter in a bet amount number(BetAmount), I would like to instantly show a calculated PotentialGain, which, for example, can be found by multiplying a constant by the specified bet amount entered in by the user.
I'm not very familiar with JavaScript, so any help is greatly appreciated!
Your code is almost correct - you are showing the result in the BetAmount field so no change is visible.
Change your code to:
document.getElementById("PotentialGain").value = ish;
Here's a working demo. I changed the event to onkeyup as onchange only happens on blur - i.e. when a field loses focus.
Here is the final JQuery function that I used.
function changeBet(bet) {
var moneyline = <?php echo json_encode($win) ?>;
var gain = moneyline * bet;
document.getElementById("PotentialGain").value = gain;
}
Along with these inputs:
<input type="text" name="BetAmount[]" id="BetAmount" onkeyup="changeBet(this.value);" >
<input type="number" name="PotentialGain" id="PotentialGain" />