SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
-
Sep 18, 2004, 19:18 #1
- Join Date
- Dec 2002
- Location
- Denver, CO
- Posts
- 2,877
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Script processing form when it's not supposed to
I have a snippet of javascript to check and make sure all the fields in a form are filled in. If they aren't then it shows an alert box telling you to put something in that form. If all the fields are filled in then it submits the form. That piece of code is this:
Code:function checkFields() { var errors = "no"; if(document.street_team.email.value == "") { alert("Please enter an e-mail address.."); errors = "yes";} if(document.street_team.name_first.value == ""){ alert("Please enter your first name."); errors = "yes";} if(document.street_team.name_last.value == ""){ alert("Please enter your last name."); errors = "yes";} if(document.street_team.loc_state.value == ""){ alert("Please enter your state."); errors = "yes";} if(document.street_team.loc_city.value == ""){ alert("Please enter your city."); errors = "yes";} if(errors != "yes"){ document.street_team.submit();} }
Code:<button onClick="checkFields()">Join</button>
-
Sep 18, 2004, 19:49 #2
- Join Date
- Jan 2002
- Location
- N 44° 56.537' W 123° 3.683'
- Posts
- 1,127
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Probably a little better way to do this is to call your function with the form's onsubmit event and return false if the form isn't completed. That should prevent submission. You might also want to consider using if/else/if statements to prevent the interpreter from having to test each if statement after one is found to be true. Only if the form passes all the tests should the function return true, allowing submission to proceed. This has the advantage of allowing those with JavaScript disabled to submit the form (albeit, with potential ommissions).
Call the function with: onsubmit="return checkFields();" in the form tag to assure that the return value delivered by the function determines if submission proceeds.
-
Sep 18, 2004, 19:50 #3
- Join Date
- Mar 2004
- Location
- Milano
- Posts
- 127
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Instead of this
Code:if(errors != "yes"){ document.street_team.submit();}
Code:if(errors != "yes"){ return true;} else { return false;}
-
Sep 18, 2004, 22:59 #4
- Join Date
- Dec 2002
- Location
- Denver, CO
- Posts
- 2,877
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Great. Problem solved!
-
Sep 19, 2004, 17:52 #5
- Join Date
- May 2003
- Posts
- 1,843
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Actually...JVLB's solution was the correct one. JavaScript should supplement your page's behavior, never - if feasible - make its functioning impossible without JavaScript.
::: certified wild guess :::
Bookmarks