尝试从表单中获取数据并将其附加到全局数组,但由于某种原因未添加数据



我试图从表单中获取数据并将其附加到全局数组中,但由于某些原因,数据没有添加到数组中。代码基本上应该接受来自表单的输入,并将其存储到全局数组中。我更新了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();
}
//Append To array

records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);



for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><a href ="index.html"><img src="New folder/logo.jpg" /></a></h1>
Information.addEventListener('submit', addnew);
}
</script>
```

首先。name属性与form元素无关。

第二。CCD_ 3没有意义,因为CCD_。

以及核心。当提交表单时,页面默认会刷新,因此addNew函数会像所有其他变量一样中止。为了防止这种情况发生,你必须按照以下步骤操作。

在提交按钮广告一个id属性:

<button id="submit" type="submit"> Submit </button>

然后在JS的顶部,获取button元素并添加一个事件监听器:

let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );

这是最后一步。在addNew函数中,添加一个事件参数。在函数代码的开头,启动preventDefault方法:

function addnew(event) {
event.preventDefault();
// the rest of the code here
}

顺便说一下。你这里有个打字错误。它应该是CCD_ 5。

if (oocu == null || oocu == "") {
alert();
}

祝你好运!

最新更新