-2

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>
Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
  • Does this answer your question? [JavaScript code to stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – Rohit Ambre Aug 08 '20 at 06:42

1 Answers1

0

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/

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
  • Thanks man this worked , I just modified it a bit by adding ```` else { alert ("error "); }```` problem is I have ```` form action ="somewhere.php"```` and by adding that javascript code the form data isn't being sent to PHP , but if I intentionally ruin the code by adding extra semicolons or brackets , that stops javascript to work .. then the data is being sent to Php , Can you figure out the solution for this please ? – Agencybackground Aug 10 '20 at 09:23
  • Does it solve your problem? https://jsfiddle.net/vyspiansky/wzv39q6a/ – Ihor Vyspiansky Aug 10 '20 at 09:39