Forum Moderators: open

Message Too Old, No Replies

Multiple of 3 required

when submitting form

         

mrnoisy

4:07 am on Sep 9, 2005 (gmt 0)

10+ Year Member



I need to check whether a form field (document.orderform.qty.value) is a multiple of 3 when a form is submitted, eg 3, 6, 9, 12 etc.

I want an alert('Must be a multiple of 3') if the user tries to submit the form if it's false.

I've done a lot of searching and have found nothing so far, any help would be greatly appreciated.

Bernard Marx

7:48 am on Sep 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if ( document.orderform.qty.value % 3!= 0 )
{
....
}

Using the modulus operator. Note that the string value is implicitly converted to a number.

mrnoisy

9:07 am on Sep 9, 2005 (gmt 0)

10+ Year Member



Thanks Bernard Marx, that works well.

I'm sure the return false; in the following function should stop the form being submitted, but after I OK the alert, the form submits anyway. Am I missing something?

<script type="text/javascript">
function three(){
if ( document.orderform.qty.value % 3!= 0 )
{
alert("Total must be multiple of 3");
return false;
}
}
</script>

<form method="post" action="process.php" name="orderform" onsubmit="three();">

Bernard Marx

9:20 am on Sep 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



onsubmit="return three();"

- It could be safe to explicitly return

true
if the input is OK.
- It will still accept negative numbers, or zero.

(using:) onsubmit="return three([blue]this[/blue]);"> 

function three(form){
var value = form.qty.value;
var OK = (value % 3 == 0) && ( value > 1 )
if (!OK )
alert("Total must be multiple of 3");
return OK;
}

mrnoisy

10:02 am on Sep 9, 2005 (gmt 0)

10+ Year Member



Brilliant, thank you.