Vangel Tzo
Vangel Tzo

Reputation: 9313

Check for empty field on form submission

I have create an eshop. I have enter an input field for 'quantity' and When i click on a submit button the products will be added in my basket. But if i press the submit button with empty the quantity field it will redirect me to an empty page.

So I want to attach an event to the form submission so that nothing is done if the quantity field is empty.

New in javascript, Thanks in advance!

Upvotes: 1

Views: 12375

Answers (4)

u936293
u936293

Reputation: 16264

It's 2017 and Html 5 and I am sure you would have already discovered:

<input name="quantity" required>

gives what you want. Or maybe even:

<input name="quantity" type="number" min="1" required>

Note that all the answers here are checking on the client side only. You have to check or handle an empty value at the server also. If an empty value (which you think will never be submitted) crashes your server app, hackers can use this to probe for vulnerabilities.

Upvotes: 4

vusan
vusan

Reputation: 5331

This code will not make your form submit if the input box is empty;

<input type="submit" onclick="return checkEmpty()">

don't forget to put return before checkEmpty()

JS

function checkEmpty() {
var valueofId=document.getElementById("myField").value;
if (!valueofId) {
        return false;
    }
}

Upvotes: 1

Sovan
Sovan

Reputation: 104

Onsubmit of the form execute a javascript method to check if value is entered or not in the field using document.getElementById('').value. If there is no value return.

Ex:

var x=document.getElementById('<your_id>').value;
if (x==null || x=="")
  {
    return false;
// redirect to where you want
  }

HTH

Upvotes: 0

Levi Botelho
Levi Botelho

Reputation: 25234

document.getElementById("formId").onsubmit = function () {
    if (!document.getElementById("myField").value) {
        return false;
    }
}

This will capture the submit action of your form and verify that a given field is not empty. Returning false interrupts the form submission. This can also be done by passing an event parameter to the function and then using e.preventDefault().

Upvotes: 6

Related Questions