JavaScript Help

Hi Everyone,

Im a student studying Web Development/Design and I am having an issue with some JavaScript for one of my assignments.

I am having trouble validating a form on submit. Everything validate nicely except for the selection list. Below is the script I have for the selection list so far:

if((!document.clientfeedback.staff.selectedIndex==0))
{
alert(“You must choose the number of staff”);
document.clientfeedback.staff.focus();
return false;
}

Any help would be greatly appreciated.

Cheers Peta

try removing the !

 
if((document.clientfeedback.staff.selectedIndex==0))
{
      alert("You must choose the number of staff");
      document.clientfeedback.staff.focus();
      return false;
}



Thank you so much! That works now.

Why would removing the ‘!’ make it work? Some of the other validations have the ‘!’

the ! means “not” and so

 
if([COLOR=red][B]![/B][/COLOR]document.clientfeedback.staff.selectedIndex==0)

means “if the selectedIndesx is not equal to 0”.

it is the same as

 
if(document.clientfeedback.staff.selectedIndex [COLOR=red][B]!=[/B][/COLOR] 0 )

The ! means NOT. You’ll also see && which means AND and || which means OR

This code says:


if (!(document.clientfeedback.staff.selectedIndex == 0)) {

If it’s NOT the case that the selected index is 0.

This part equates to TRUE
document.clientfeedback.staff.selectedIndex == 0

And the ! inverts that, to mean FALSE.
!(TRUE) is FALSE

You however, want the condition to be true when the selected index is zero instead.


if(document.clientfeedback.staff.selectedIndex == 0) {

Thanks everyone for your replies.

Im slowing learning JavaScript and this helps me understand it better :slight_smile:

in case you are not aware, one of many very good resources on the www for javascript is the w3schools javascript tutorials

[edit]Thread split off to Is w3schools now out of date?
Please post replies to this post over there.[/edit]

Those tutorials are getting out of date.

Just looking at one example of submitting a form, the problems are:

[list][]inline event attributes and inline scripting are used, whereas traditional scripting events (or even advanced ones) are now the favored technique
[
]Script is in the head, whereas we now put our scripts at the bottom
[*]A button is used to trigger the script to submit the form, whereas a standard submit button should be used instead[/list]

In fact, their example code can be completely replaced with HTML only code, no scripting. Their scripting example provide no benefit over standard techniques.

Actually, their scripted form example completely fails to work at all when scripting is not available. This surprizingly means that an HTML-only solution is superior in practice to their script coded example. Not a good look.

Most of their other code examples face similar “out of date” problems too.

w3schools used to be a good resource, but it has long since been surpassed by the passage of time and circumstance.