0

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>

2 Answers 2

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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();

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.