简体   繁体   中英

Attempting to prevent submitting empty form

I have a form in my HTML document, and it only has a "text" input, and a submit button. I also have JavaScript that checks if the field is empty and returns true or false.

JSFiddle: http://jsfiddle.net/HBZ7t/

HTML:

<form onsubmit="checkNull();" method="post">
<input type="text" id="field">
<input type="submit">
</form>

JavaScript

function checkNull() {
var field = document.getElementById("field");
    if(field.value !== "") {
    return true;
    }
return false;
}

However, the form can be submitted even if the text field is empty... Any suggestions?

You are doing nearly everything right, you just need to return the value from the function to the handler:

<form onsubmit="return checkNull();" method="post">
// -------------^^^^^^

In JavaScript you can use double exclamation points to check for lots of non-valid settings:

function checkNull() {
  var field = document.getElementById("field");
  if(!!field.value) {
    return true;
  } else {
    return false;
  };

FIDDLE

JS

var form=document.getElementById("form");
form.onsubmit=function(){
 var field = document.getElementById("field");
    if (field.value !== "") {
        return true;
    }
    return false;
};

HTML

<form id="form" method="post">
    <input type="text" id="field">
    <input type="submit">
</form>

you can use event.preventDefault() to cancel a event, see mozila doc here

Also, check the very nice jQuery submit function and samples here

Check this sample: http://jsfiddle.net/HBZ7t/5/

$( "#target" ).submit(function( event ) {

  if($('#field').val()=='')
  {
    alert('cancel event');
    event.preventDefault();
  }

});

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