如何仅在表单不为空时重定向,JavaScript验证



现在,即使输入字段为空,如果按下提交按钮,也会显示警报"消息":然后重定向到窗口;URL";

我要找的是,如果输入字段已填充,它只显示已完成的警报和重定向

<form>
<input type="text" placeholder="enter name here">
<input type="number" placeholder="enter number here">
<input type="submit" id="submitbutton" value="submit">
</form>
</center>
</body>

<script type="text/javascript">
const submitit = document.getElementById('submitbutton');
submitit.addEventListener("click",function(){
alert("Done, Meanwhile check our website");
window.location="https://www.google.com";   
});
</script>

试试这个

<form>
<input id="name" type="text" placeholder="enter name here">
<input id="number" type="number" placeholder="enter number here">
<input type="submit" id="submitbutton" value="submit">
</form>

和JavaScript:

const submitit = document.getElementById('submitbutton');
submitit.addEventListener("click", function(e) {
// prevent form from being submitted
e.preventDefault();
alert("Done, Meanwhile check our website");
const name = document.getElementById('name');
const number = document.getElementById('number');
if (name.value !== '' && number.value !== '') {
window.location = "https://www.google.com"; 
}  
});

演示-https://jsfiddle.net/vyspiansky/v7yjwL6x/

相关内容

  • 没有找到相关文章

最新更新