[英]HTML,javascript: on button click validation not working
我試圖驗證(如果他們有價值)我的html的前兩個下拉列表。 點擊按鈕getURL
我正在驗證下拉列表中是否有任何選定的值,如果是,我想繼續使用function getURL
。
但是在驗證后不久,如果第二個Dropbox中沒有值,則控件不會停止。 它繼續並顯示URL
。
我想只在前兩個下拉列表中有值時才顯示URL
。 但現在使用我的下面的代碼我會收到alert:url
alert:select product version
后不久的alert:url
alert:select product version
使用Javascript:
function validate() {
var pname = document.getElementById("selProductName");
if(pname.selectedIndex == 0) {
alert('select product name');
}
var pversion = document.getElementById("selProductVersion");
if(pversion.selectedIndex == 0) {
alert('select product version');
return false;
}
return true;
}
function getURL() {
validate();
// I have code here to create desired URL
alert("url:" + url);
}
HTML:
Product Name:
<select id="selProductName" name="selProductName" onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>
<br>Product Version:
<select id="selProductVersion" name="selProductVersion" onchange="changeProductVersion(this.value);">
</select>
<br>File Name:
<select id="selFileName" name="selFileName"></select>
<br><button onclick="getURL()">Get URL</button>
validate()
執行並返回false。 好。 接着? 然后腳本繼續並提醒網址。
目前 :
function getURL() {
validate(); // Returns true or return false, no consequence.
alert("url:" + url); // Always happens.
}
你應該使用:
function getURL() {
if(!validate()) return; // Blocks execution if validation fails.
alert("url:" + url);
}
您的驗證功能正是如何工作的。 問題是你永遠不會檢查以確保驗證沒有返回false。 相反,即使validate()確實返回false,您也只是打印URL。 這是一個應該有效的getURL()函數的編輯版本。
function getURL() {
var isValid = validate();
// Code to create URL
// Only alert the formed URL if isValid doesn't equal false
if(isValid != false) alert("url:" + url);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.