gpt4 book ai didi

javascript - 我想在 JavaScript 中验证我的必填字段不为空

转载 作者:行者123 更新时间:2023-11-30 10:37:47 25 4
gpt4 key购买 nike

希望这是基本的 JavaScript,并且答案很简单,因为我是新手。我只想确保在用户可以继续之前所有必填字段都不为空。在我的 <form> action = payment.php并且提交按钮包含 onclick="insert();"当 child_name 留空时,它只是继续到下一页而不是提醒。这是代码:

    <script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XLMHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}



cn1 = 'child_name'+document.getElementById('child_name').value;
ag2 = 'age'+document.getElementById('age').value;
hm3 = 'hometown'+document.getElementById('hometown').value;
bg4 = 'boy_girl'+document.getElementById('boy_girl').value;
fn5 = 'first_name'+document.getElementById('first_name').value;
ln6 = 'last_name'+document.getElementById('last_name').value;
email = 'email'+document.getElementById('email').value;
ad8 = 'address1'+document.getElementById('address1').value;
ad9 = 'address2'+document.getElementById('address2').value;
ct10 = 'city'+document.getElementById('city').value;
st11 = 'state'+document.getElementById('state').value;
zp12 = 'zip'+document.getElementById('zip').value;

if (cn1.equals("")) {


xmlhttp.open('POST', 'payment.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(cn1&ag2&hm3&bg4&fn5&ln6&email$ad8&ad9&ct10&st11&zp12);
} else {
alert ("Please enter all required fields.");
}
}
</script>

最佳答案

这里有几个问题:

cn1 = 'child_name'+document.getElementById('child_name').value;

在这种情况下,您将 cn1 分配给字符串 'child_name' + child_name 文本框的值...它永远不会等于空字符串。

其次,您需要 insert() 方法在出错时返回 false 以停止按钮的预期操作。

关于javascript - 我想在 JavaScript 中验证我的必填字段不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12975734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com