Hussain Khalil
Hussain Khalil

Reputation: 1650

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?

Upvotes: 2

Views: 77

Answers (4)

RobG
RobG

Reputation: 147393

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">
// -------------^^^^^^

Upvotes: 2

Danyu
Danyu

Reputation: 507

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

});

Upvotes: 0

Maulik Anand
Maulik Anand

Reputation: 1449

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>

Upvotes: 1

Alan Wells
Alan Wells

Reputation: 31300

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

Upvotes: 1

Related Questions