简体   繁体   中英

Return true doesn't work for javascript on button click

I have a Javascript code that returns true if a certain checkbox is checked.


document.getElementById("accept").addEventListener("click", function(event){
if(document.getElementById('hck').checked == false){
  event.preventDefault();
}
else
{
 return true;
}   

});

This is the Javascript code

<input class="btn btn-success btn-lg mx-auto btnac" type="submit" id="accept" name="accept" value="Accept">

This is the button and it's inside a form.

I had put in two print statements earlier to see if it enters the clauses, and it does, but it doesn't go to the Django function and return the appropriate page on return true.

我建议您最好为案例使用required属性

You can use the required attribute as suggested by others already but to also resolve your original attempt here's a working example of what you tried to achieve.

The form submits when checkbox is checked otherwise it doesn't.

 document.getElementById("accept").addEventListener("click", function(event){ if(document.getElementById('hck').checked) { console.log('checkbox is checked'); return true; } console.log('checkbox is not checked'); event.preventDefault(); });
 <div> <form action="#something" method="get"> <input type="checkbox" id="hck" name="hck" value="Test Box"> <br/> <input class="btn" type="submit" id="accept" name="accept" value="Accept"> </form> </div>

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