小唯快跑啊
2023-08-05 19:38:47
我試圖從表單中獲取數據并將其附加到全局數組中,但由于某種原因,數據沒有添加到數組中。代碼基本上應該接受來自表單的輸入并將其存儲到全局數組中。我更新了 HTML,以便您可以看到完整的語法。該值基本上應該從表單中獲取并使用“addnew”函數放入全局數組中。 function addnew() { //calculateAge(); //Accept values entered in form const fname = document.getElementById('fname').value; const mname = document.getElementById('mname').value; const lname= document.getElementById('lname').value; const dob= document.getElementById('dob').value; const genderM = document.getElementsByName('male').checked; const genderF = document.getElementsByName('female').checked; const age = calculateAge.bYear; const bodyType = document.getElementById('Body Type').value; const occu= document.getElementById('occu').value; const height= document.getElementById('height').value; if (fname==null || fname=="") { alert(); } if(mname==null || mname=="") { alert(); } if (lname==null || lname=="") { alert(); } if(dob==null || dob=="") { alert(); } if (genderM.checked == false || genderF.checked == false){ alert(); } if (age <=18 || age >=75) { alert(); } if(height>=170 || height<=200) { alert(); } if(bodyType==null || bodyType==""){ alert(); } if(oocu==null || oocu=="") { alert(); } </script>
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
首先。name屬性與元素無關form。
第二。Information.addEventListener('submit', addnew);沒有意義,因為Information沒有定義。
并深入到核心。提交表單時,頁面默認刷新,因此 addNew 函數像所有其他變量一樣中止。為了防止這種情況,您必須執行以下操作。
提交按鈕廣告上有一個 id 屬性:
<button id="submit" type="submit"> Submit </button>
然后在 JS 之上,獲取按鈕元素并向其添加事件偵聽器:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
這是最后一步。在 addNew 函數上,添加一個事件參數。并在函數代碼的開頭,觸發 PreventDefault 方法:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
順便一提。你這里有一個錯字。應該是的occu。
if (oocu == null || oocu == "") {
alert();
}
祝你好運!
添加回答
舉報
0/150
提交
取消