...

View Full Version : Javascript multiple If operators



GlynD02
06-07-2010, 06:47 PM
Hi there people

I am new to Javascript and have come accross a problem where I need to check the value of a field on a form before it is submitted. It has to be either a whole number OR a particular text value...

I have added the following code before the form is submitted. However even if the value of the field is a whole number or it is the correct text string, the message box still pops up and the form fails to submit!


if ((document.AddNewVA.HourlyRate.value!='neg') || (isNaN(document.AddNewVA.HourlyRate.value*1)))
{
// Not the correct text OR a whole number in the HourlyRate field...
alert('Please enter a whole number or \"neg\" in the Hourly rate field...');
document.AddNewVA.HourlyRate.value = "0";
document.AddNewVA.HourlyRate.focus();
return false;
}

Can anyone point me in the right direction please?

Many thanks

randomuser773
06-07-2010, 07:51 PM
if ((document.AddNewVA.HourlyRate.value!='neg') || (isNaN(document.AddNewVA.HourlyRate.value*1)))
{
If the input is a number then it can't be 'neg' so you will get the alert, while if it is 'neg' then it can't be a number so it will alert. It needs to ask another question perhaps with a different operator

GlynD02
06-07-2010, 10:28 PM
Thanks for that RandomUser. So would another nested "If" statement be the solution then please?

I did try some experimenting with the following code:


if (document.AddNewVA.HourlyRate.value!='100' || document.AddNewVA.HourlyRate.value!='200')
{
alert('Please enter 100 OR 200 in the Hourly rate field...');
}


...and I still got the prompt up even if I entered 100 or 200 into the text box...

Cheers

randomuser773
06-07-2010, 11:03 PM
Thanks for that RandomUser. So would another nested "If" statement be the solution then please? No


I did try some experimenting with the following code:


if (document.AddNewVA.HourlyRate.value!='100' || document.AddNewVA.HourlyRate.value!='200')
{
alert('Please enter 100 OR 200 in the Hourly rate field...');
}


...and I still got the prompt up even if I entered 100 or 200 into the text box...

CheersAt least one of those tests is always going to evaluate true, therefore you will always get the alert. https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#Logical_Operators

GlynD02
06-08-2010, 01:27 PM
Thanks RandomUser

I looked at it again and changed it from a Logical OR to a Logical AND i.e.


if ((document.AddVA.HourlyRate.value!='Neg') && (isNaN(document.AddVA.HourlyRate.value*1)))

Which has now done the trick...
:thumbsup:

Cheers



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum