How to Redirect only if form is not empty , JavaScript Validation

只谈情不闲聊 提交于 2020-08-20 16:03:42

问题


Right now even if input fields are empty , if submit button is pressed it shows alert"message": and then redirects to window.location="URL"

What I m looking for is it only shows done alert and redirects if input fields are filled

        <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>

回答1:


Try this

<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>

and 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"; 
  }  
});

Demo - https://jsfiddle.net/vyspiansky/v7yjwL6x/



来源:https://stackoverflow.com/questions/63312470/how-to-redirect-only-if-form-is-not-empty-javascript-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!