简体   繁体   中英

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!

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() .

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.

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

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

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