简体   繁体   中英

JavaScript Form validation doesn't stop the submit

I have a form which includes some checkboxes:

<form class="lightblue" action="someValidRef" method="post" onsubmit="return client_validation(this)">
...
<div>
      <label>Label</label>
      <ul>
        <li><input type="checkbox" name="land" value="Austria">Austria</li>
        <li><input type="checkbox" name="land" value="Belgium">Belgium</li>
        <li><input type="checkbox" name="land" value="Bulgaria">Bulgaria</li>
        <li><input type="checkbox" name="land" value="Czech Republic">Czech Republic</li>
        <li><input type="checkbox" name="land" value="Switzerland">Switzerland</li>
        <li><input type="checkbox" name="land" value="Germany">Germany</li>
        <li><input type="checkbox" name="land" value="Denmark">Denmark</li>
        <li><input type="checkbox" name="land" value="Spain">Spain</li>
        <li><input type="checkbox" name="land" value="Estland">Estland</li>
    </ul>
</div>
...
<div>
        <input type="submit" name="submit" value="send" />
        <input type="reset" name="reset" value="reset" />
</div>

with following JS:

<script language="JavaScript1.2">
function client_validation(theForm)
{
    ...
    var land = theForm.land;
    var land_set = false;
    for (i = 0; i < land.length; i++) {
      if (land[i].checked) {
        land_set = true;
      }
    }
    if(!land_set){
        alert("please choose a country");
        theForm.land.focus();
        return (false);
    }   
    ...
  return true;
}
</script>

I omitted other form fields and other validation parts for this post. Every other part of the validation is working, but this list of checkboxes counteracts every validation. While a country is selected, it works fine and other validations are executed as well. But as soon as I click on submit while no country is selected, my form still submits . It even gives me the alert saying "please choose a country", but upon closing this message, the form is submitted... Why is it still submitting? I tried changing the "return true" statement in the end of the validation to return land_set , but it's not working either.

 theForm.land.focus();

The above line of code in your function is throwing an error and control never gets to the line return (false); . That's why it is not preventing the page submit.

You can fix the error by doing this:

theForm.land[0].focus();

Since land is an array, that's why the error was occurring.

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