-1

i want to stop reloading page when i don't choose category and click on submit button. can anybody help me?

function check() {
  var select = document.getElementById("category").value;
  if (select == -1) {
    return alert("You didn't choose category !!!");
  }
}
<form action="#" method="POST" id="form" name="form">
  <select name="category" id="category">
        <option value="-1">Select category</option>
        <option value="1">News</option>
        <option value="2">Sport</option>
        <option value="3">World</option>
        <option value="4">Music</option>
    </select>
  <input type="submit" value="submit" id="submit" name="submit" onclick="check();" />
</form>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
Dejan
  • 1
  • 1
  • 5

2 Answers2

0

You need to return false from the function to prevent the form from beeing submitted.

<input type="submit" value="submit" id="submit" name="submit" onclick="return check();" />

function check() {
    var select = document.getElementById("category").value;
    if (select == -1) {
        alert("You didn't choose category !!!");

        return false;
    }
}
Lars Beck
  • 3,446
  • 2
  • 22
  • 23
0
<form action="#" method="POST" id="form" name="form">
<select name="category" id="category">
    <option value="-1">Select category</option>
    <option value="1">News</option>
    <option value="2">Sport</option>
    <option value="3">World</option>
    <option value="4">Music</option>
</select>
<input type="button" value="submit" id="submit" name="submit" onclick="check();" />

An alternative response is to set the type in "button" with this method you can check the state without reload the page.

And in the javascript if you want to send the submit you can put this code.

document.getElementById("form").submit(); 

Here there is an example https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_form_submit