简体   繁体   中英

how do i stop alert box from closing out itself?

 document.getElementById("error").style.display = "none"; document.getElementById("submit").onclick = function() { document.getElementById("error").style.display = ""; }
 .alert-er { padding: 20px; background-color: #ff2400; color: #ffffff; font-size: 20px; border: 1px solid white; border-radius: 20px; }.closebtn { margin-left: 15px; color: white; font-weight: bolder; float: right; font-size: 40px; line-height: 20px; cursor: pointer; transition: 0.3s; }.closebtn:hover { color: black; }
 <div id="error" class="alert-er"> <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> <strong>Error!</strong> </div> <form> <button type="submit" id="submit" class="submit">Submit</button> </form>

a tried to display a alert box showing error and it worked fine until i changed display properties. now it appears and then disappears automatically in less than a second. i tried cheking for errors. i changed codes different times using css, js and jquery. but in all of those cases happened the same. please do care to help.

Try using

type="button"

in

<button type="button" id="submit" class="submit">Submit</button></form>

<div id="error" class="alert-er">
    <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> 
    <strong>Error!</strong> 
</div>  
<form>
    <button type="button" id="submit" class="submit">Submit</button>
</form>

The problem is that when you click the submit button, the form is being submitted.

To fix this, let's create an event listener for when the form is submitting. If we find an error, we don't let it continue the submission, and show the error message instead. We do this with the help of event.preventDefault():

const form = document.querySelector('form');
const errorMessage = document.getElementById("error");

form.addEventListener('submit', (event) => {

  if(thereIsAnError()){
    event.preventDefault();
    errorMessage.style.display = "block";
  }

})

function thereIsAnError(){
    return true; // later, change this function to return true or false depending on your input values
}

document.getElementById("error").style.display = "none";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM