简体   繁体   中英

Javascript function runs twice when validating form

I'm sure there must be a simple explanation to this. I'm trying to get an alert 'Country must be selected' to appear whenever the option 'Not Selected' is selected (it is selected by default I believe), and clicking on the validation button . I have been able to get the function to show the alert correctly, but the problem is that the alert shows twice.

Why does the alert show twice, and how can I get it to show only once? thanks!

 function CountrySelectValidation() { // ensures country is selected var ValidateCountry = document.forms["registration-form"]["Country"].value; if (ValidateCountry == "not-selected") { alert("Country must be selected"); return false; } else { return true; } } function SubmitForm() { if (CountrySelectValidation()) { // check if true, then execute this code document.getElementById("registration-form").submit(); } } 
 <form id="registration-form"> What country are you from? <select name="Country"> <option value="not-selected">Not Selected</option> <option value="england">England</option> <option value="wales">Wales</option> <option value="scotland">Scotland</option> <option value="northern-ireland">Northern Ireland</option> </select> <br><br><input type="submit" value="Submit Method 1"> <button type="reset">Reset Method 1</button> <button type="submit" id="submit-2">Submit Method 2</button> </form> <button onClick="ResetForm()">Reset Method 1</button> <button onClick="CountrySelectValidation(); SubmitForm()">Validation</button> 

CountrySelectValidation()
...
if (CountrySelectValidation())

You run the CountrySelectValidation function inside the if (it actually executes), so that's why it runs twice.

You are executing the function again when you call the if statement. Run the code from the if statement in a different function called inside the original function.

OriginalFunction () {

      //Content here

      FunctionToHandleIfstatement();

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM