how to stop reloading page after alert in javascript [duplicate]

↘锁芯ラ 提交于 2021-02-08 12:01:19

问题


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>

回答1:


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



回答2:


<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



来源:https://stackoverflow.com/questions/44758835/how-to-stop-reloading-page-after-alert-in-javascript

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