check condition before submitting form in jquery - javascript

I am submitting a frm that is basically an invoice of purchase. before submitting the form i want to implement the check that the user doesn't enter amount more than the total bill in the text box.for example if total bill is 300 and in the "paid amount" text box user enters 3000 accidentally then it should show the error message here is my code:
$("#mainform").submit(function() {
var total = $("#gtotal").val();
var paid = $("#paid").val();
alert(paid);
alert(total);
if(paid > total)
{
alert("Amount can't be greater than total");
return false;
}
return true;
});
when I alert paid and total amount they show correct values, but the if condition is not working some times it submits the form if the condition is not fulfilled sometimes i doesn't even condition is fulfilled

Try this, it may work:
var total = parseInt($("#gtotal").val());
var paid = parseInt($("#paid").val());

.val() returns strings
Convert paid and total to float with parseFloat, check them with isNaN, then compare. Like so:
paid = parseFloat(paid);
total = parseFloat(total);
if (!isNaN(paid) && !isNaN(total)) {
if (paid > total) {
...
If you aren't using decimals you may use parseInt

Add a parameter on submit function and call preventDefault method to avoid form to be submitted.
.submit(function(event) {
...
if (paid > total) {
...
event.preventDefault();
}

There are some conditions missed:
empty input field
not a number
In order to convert a string to number you can prefix the string with a plus sign.
A solution could be:
$("#mainform").on('submit', function(e) {
var total = +$("#gtotal").val();
var paid = +$("#paid").val();
if (($("#gtotal").val().trim().length == 0) || isNaN(total)) {
console.log("Please specify total");
$("#gtotal").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if (($("#paid").val().trim().length == 0) || isNaN(paid)) {
console.log("Please specify paid");
$("#paid").focus();
e.preventDefault();
//
// stop function execution....
//
return;
}
if(paid > total) {
console.log("Amount can't be greater than total");
//
// prevent the submit action
//
re.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="mainform" action="http://www.google.com">
gtotal: <input id="gtotal" type="text">
paid:<input id="paid" type="text">
<input type="submit" value="Submit Form">
</form>

Related

Can't get textbox input converted to an integer?

I am trying to create a program that takes a user input number and compares it to a randomly generated number until the user guesses the correct number. I was having a problem where my user input number is showing up undefined while I am debugging my program but I used parseInt and fixed the issue. Now it seems it is an issue with my if else statement because I get the right use input number back now when I run a debug on my code but it now when I run it, even when I enter 1000 as my guess, it always gives me "Your guess is too low! Try a higher number."
var guessNum;//user input guess
function randomNumber(guessNum1)
{
guessNum = document.getElementById( "numInput" ).value;//getting value of user input
var guessNum1 = parseInt(guessNum);//change user input to integer
var num = Math.floor( 1 + Math.random() * 1000 ); //random number generator
if (num == guessNum1)
{
messages.innerHTML = "Congratulations! You guessed the number!";
}
else if (num < guessNum1)
{
messages.innerHTML = "Your guess is too high! Try a lower number.";
}
else (num > guessNum1)
{
messages.innerHTML = "Your guess is too low! Try a higher number.";
}
guessNum = document.getElementById( "numInput" ).value = "";//clears the textbox on screen
}
function start()
{
var guessButton = document.getElementById( "guess" );//variable for clicking button
guessButton.addEventListener( "click", randomNumber, false);
//event listener for button that starts randomNumber function
messages = document.getElementById( "messages" );
}
window.addEventListener( "load", start, false);//starts start function on screen load
<h1>Guess the Number!</h1>
<h3>Enter in a number between 1-1000 in the textbox and hit submit </h3>
<form action = "#">
<input id= "numInput" type="text" >
<input id= "guess" type="button" value="Guess" >
</form>
<p id= "messages">Enter a number to start the game </p>

How to set a check if coupon code used one time then do not allow to use it second time in one transection

This is my code
html input field
<input type="text" size = "3" name="couponadd" id="couponadd"
oninput="myFunction()" class="field" placeholder="Enter Coupon Code" />
Script Code
<script>
var lastval;
function myFunction() {
getting CouponDC,TicketypDC and CouponPrcDC from database
var CouponDC = $('#dbcoupan').val();
var TicketypDC = $('#dbtckettype').val();
var CouponPrcDC = $('#dbprice').val();
var total_price = $('#total_price').val();
Get getcoupon from input
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
check if user enter same coupon
if(getcoupon == lastval )
{
alert('You Cant Enter Same Code Again');
}
if coupon code match with database coupon
else if (getcoupon == CouponDC ) {
$amount=CouponPrcDC;
total_price = total_price * ((100-$amount) / 100);
minus some ammout from total if match
total_price = Math.round(total_price);
document.getElementById('Voucher_value').value = total_price;
}
if coupo don't match with database coupon
else if(getcoupon != CouponDC && getcoupon.length ==5 )
{
alert('WRONG COUPON CODE');
}
**store last value enter in input**
lastval = getcoupon;
$('#total_price').val(total_price);
}
</script>
You can store it in an array and check if it exists before moving ahead.
Pseudo code below:
var couponArr = [];
var getcoupon = $("#couponadd").val();
if($.inArray(getcoupon, couponArr) !== -1) {
alert('Coupon already used, can\'t use again.');
} else {
couponArr.push(getcoupon);
// your code here..
}
inArray returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1 will be returned.
Add a global tag variable and set default to false,use a if condition wrap the code need to run,then in the run code set it to true.
such as:
// in outer space
var hasCodeRun = false;
// in some function
if (!hasCodeRun) {
// run code here
hasCodeRun = true;
}

Limiting input field to one decimal point and two decimal places

I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?
This is my input field
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
Here is my validation script.
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var amount = parseFloat($(this).val());
if (amount) {
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Jonah
This should do :
var ok = /^\d*\.?\d{0,2}$/.test(input);
(if I correctly understood that you don't want more than 2 digits after the dot)
The code thus would be :
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Assuming that:
There MUST have 2 digits after a decimal point, and
There must be at least 2 digits before the decimal point, but no more than 3 digits
The code you would use to match it would be:
var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);
It would be much easier if you used the Masked Input Plugin for jQuery.

Get form fields to hide and populate

I have a 3 fields:
Total amount
Recurring amount
Occurrences
A user will always enter occurrences, but has the choice of entering either total amount or recurring amount.
The equation for this is really simple:
Occurrences * Recurring Amount = Total Amount
I need help making a Javascript function which if the user starts to type in the total amount field, recurring amount becomes disabled. The same is true if they enter recurring amount first. Once the user has input occurrences and either of the amounts, the remaining amount should be calculated and replace the disabled field.
I need the function to be able to allow the user to change any of the numbers, and have the calculation be re-done. Also, if the user totally removes a value from an amount, the other amount field should become active again.
I've never written Javascript code before, only edited. Any help to point me in the right direction is appreciated. Thanks
Not sure why you think disabling fields is a good idea. I think user experience-wise it would be better to allow them to edit any field at any time, adjusting the other fields as needed.
<input id="recurring" onchange="onRecurEdit()"> *
<input id="occurences" onchange="onOccurEdit()"> =
<input id="total" onchange="onTotalEdit()">
<script>
var recur = document.getElementById('recurring');
var total = document.getElementById('total');
var occur = document.getElementById('occurences');
function onTotalEdit() {
recurring.value = total.value / occur.value;
}
function onRecurEdit() {
total.value = occur.value * recur. value;
}
function onOccurEdit() {
total.value = occur.value * recur. value;
}
</script>
Here's partly what you may be looking for: The code uses JQuery
JS code:
$(document).ready(function() {
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
function calculateTot(evt) {
var o = Number($("#occur").val());
var a = Number($("#recAmt").val());
if(!isNaN(0) && !isNaN(a)) {
var tot = roundNumber(o * a, 2);
$("#totalAmt").val(tot);
}else {
$("#totalAmt").val("0");
}
}
$("#occur").bind("change", calculateTot);
$("#recAmt").bind("change", calculateTot);
});
HTML for the same:
<input type="text" id="occur" /> *
<input type="text" id="recAmt" /> =
<input type="text" id="totalAmt" readonly="readonly" />
This won't be perfect but it should be a decent start:
You can view an interactive demo of this code at http://jsfiddle.net/qzxf7/
You haven't given us your HTML so I'm going to assume you're using something like this:
<form action="" method="POST">
<input type="text" name="occurences" id="occurences" value="" />
<input type="text" name="recurringAmt" id="recurringAmt" value="" />
<input type="text" name="totalAmt" id="totalAmt" value="" />
</form>
If you haven't dealt with Javascript before, I'm going to recommend you use jQuery which is a matter of importing the jQuery script in your HTML <head>.
Using jQuery you could start with code like this which is overly complicated but throws you into how to handle the disabled stuff as well as value updates.
/* On page contents loaded */
function updateForm() {
var occ = $('#occurences');
var occV = parseFloat(occ.val());
occV = occV >= 0 ? occV : 0;
var rec = $('#recurringAmt');
var recV = parseFloat(rec.val());
recV = recV >= 0 ? recV : 0;
var tot = $('#totalAmt');
var totV = parseFloat(tot.val());
totV = totV >= 0 ? totV : 0;
/* If total is disabled */
if (tot.attr("disabled")) {
if (rec.val() == '') { /* if no text in rec */
tot.removeAttr("disabled"); /* Reenable total */
tot.val('');
return;
}
/* Otherwise update total */
tot.val(recV * occV);
return;
}
/* If rec is disabled */
if (rec.attr("disabled")) {
if (tot.val() == '') { /* if no text in total */
rec.removeAttr("disabled"); /* Reenable rec */
rec.val('');
return;
}
/* Otherwise update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
/* Otherwise neither disabled */
if (recV > 0) { /* if rec has a number value */
tot.attr("disabled", true); /* disable total */
tot.val(recV * occV); /* update total */
return;
}
if (totV > 0) { /* if total has a number value */
rec.attr("disabled", true); /* disable rec */
/* Update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
}
$(document).ready(function() {
$('#occurences').keyup(function(){
updateForm();
});
$('#totalAmt').keyup(function(){
updateForm();
});
$('#recurringAmt').keyup(function(){
updateForm();
});
});

How to check for empty values on two fields then prompt user of error using javascript

I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>

Categories