2012-05-30 185 views
0

這個腳本的功能主要是我希望如何:當收音機複選框沒有被選中時發出警報。但是,如果所有按鈕都被選中,我需要它提交的表單......這就是我掛斷的地方。現在,如果所有字段和按鈕都被選中,那麼我仍然會收到一個警報,其中包含var alertMsg。有任何想法嗎?經過驗證的Javascript表單提交

function submitform() { 
    var sizeChoice = "" 
    var size = document.store.on1.length 
    var fontChoice = "" 
    var len = document.store.on2.length 
    var materialChoice = "" 
    var material = document.store.on3.length 
    var treatmentChoice = "" 
    var treatment = document.store.on4.length 
    var a = document.forms["store"]["item_name"].value; 
    var alertMsg = "Please Choose a:" 
    for(i = 0; i < size; i++) { 
     if(document.store.on1[i].checked) { 
      sizeChoice = document.store.on1[i].value 
     } 
    } 
    for(i = 0; i < len; i++) { 
     if(document.store.on2[i].checked) { 
      fontChoice = document.store.on2[i].value 
     } 
    } 
    for(i = 0; i < material; i++) { 
     if(document.store.on3[i].checked) { 
      materialChoice = document.store.on3[i].value 
     } 
    } 
    for(i = 0; i < treatment; i++) { 
     if(document.store.on4[i].checked) { 
      treatmentChoice = document.store.on4[i].value 
     } 
    } 
    if(a == null || a == "") alertMsg += "\n" + "Name" + "\n"; 
    if(sizeChoice == "") { 
     alertMsg += "Size" + "\n" 
    } 
    if(fontChoice == "") { 
     alertMsg += "Font" + "\n" 
    } 
    if(materialChoice == "") { 
     alertMsg += "Material" + "\n" 
    } 
    if(treatmentChoice == "") { 
     alertMsg += "Treatment" + "\n" 
    } { 
     alert(alertMsg) 
    }; 
    return false; 
    document.forms["form"].submit(); 
}; 
+0

你在最後一個'if'語句後面有一個語法錯誤,看起來像是一個額外的括號。也就是說,你知道'我'是全球性的,你可能想在某個地方定義它。 – elclanrs

回答

2

無論您的驗證如何,您都會返回false。從改變你的代碼的末尾:

if(treatmentChoice == "") { 
    alertMsg += "Treatment" + "\n" 
} { 
     alert(alertMsg) 
}; 
return false; 
document.forms["form"].submit(); 

到:

if(treatmentChoice == "") { 
    alertMsg += "Treatment" + "\n" 
} 
if(alertMsg.length > 16) { 
    alert(alertMsg); 
    return false; 
} else { 
    document.forms["form"].submit(); 
} 

長度檢查檢查ALERTMSG的終值長度反對什麼您最初設置它。

-1
var alertMsg = ""; 

//.... 

if(alertMsg) { 
    alert("Please Choose a:" + alertMsg); 
} else { 
    document.forms["form"].submit(); 
} 

並請加;到每個語句。

+1

alertMsg從「請選擇一個:」開始,那麼它何時會評估爲false? – j08691

+0

xdazz,我不清楚這如何幫助。你能澄清嗎? (除了分號;)同意100%) – jmort253

+0

@ j08691我錯過了,現在編輯。 – xdazz

2

您在表單提交之前有回報。這可能是問題的一部分。

此外,你在最後的if語句中缺少一個else。

+0

+1 return語句會阻止運行後的任何其他代碼。 – jmort253

1

你在表單提交之前返回,所以它永遠不會被調用。