2017-03-25 12 views
0

これについて簡単な説明があるはずです。 「選択されていない」オプションが選択されている(デフォルトでは選択されている)ときは、「国を選択する必要があります」というアラートを表示し、のをクリックします。私は、警告を正しく表示する機能を得ることができましたが、問題はアラートが2回表示されることです。フォームの検証時にJavascript関数が2回実行される

なぜアラートが2回表示され、1回だけ表示されるのですか?ありがとう!

function CountrySelectValidation() { // ensures country is selected 
 
\t var ValidateCountry = document.forms["registration-form"]["Country"].value; 
 
\t if (ValidateCountry == "not-selected") { 
 
\t \t alert("Country must be selected"); 
 
\t \t return false; 
 
\t } else { 
 
\t \t return true; 
 
\t } 
 
} 
 

 
function SubmitForm() { 
 
    if (CountrySelectValidation()) { 
 
     // check if true, then execute this code 
 
     document.getElementById("registration-form").submit(); \t 
 
    } 
 
}
<form id="registration-form"> 
 
    What country are you from? 
 
    <select name="Country"> 
 
\t \t <option value="not-selected">Not Selected</option> 
 
\t \t <option value="england">England</option> 
 
\t \t <option value="wales">Wales</option> 
 
\t \t <option value="scotland">Scotland</option> 
 
\t \t <option value="northern-ireland">Northern Ireland</option> 
 
\t </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>

答えて

1

ifステートメントを呼び出すときに関数を再度実行しています。元の関数内で呼び出された別の関数のif文からコードを実行します。

OriginalFunction() { 

     //Content here 

     FunctionToHandleIfstatement(); 

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

あなたは(それが実際に実行される)ifCountrySelectValidation機能を実行し、それが二回走る理由です。

関連する問題