Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if html form values are empty using Javascript

I want to check a form if the input values are empty, but I'm not sure of the best way to do it, so I tried this:

Javascript:

  function checkform()
    {
      if (document.getElementById("promotioncode").value == "")
    {
        // something is wrong
        alert('There is a problem with the first field');
        return false;
    }

    return true;
    }

html:

  <form id="orderForm" onSubmit="return checkform()">
      <input name="promotioncode" id="promotioncode" type="text" />
      <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/>
      <input class="submit" type="submit" value="Submit"/>
  </form>

Does anybody have an idea or a better solution?

like image 275
vicR Avatar asked Dec 16 '22 06:12

vicR


2 Answers

Adding the required attribute is a great way for modern browsers. However, you most likely need to support older browsers as well. This JavaScript will:

  • Validate that every required input (within the form being submitted) is filled out.
  • Only provide the alert behavior if the browser doesn't already support the required attribute.

JavaScript :

function checkform(form) {
    // get all the inputs within the submitted form
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        // only validate the inputs that have the required attribute
        if(inputs[i].hasAttribute("required")){
            if(inputs[i].value == ""){
                // found an empty field that is required
                alert("Please fill all required fields");
                return false;
            }
        }
    }
    return true;
}

Be sure to add this to the checkform function, no need to check inputs that are not being submitted.

<form id="orderForm" onsubmit="return checkform(this)">
    <input name="promotioncode" id="promotioncode" type="text" required />
    <input name="price" id="price" type="text" value="&euro; 15,00" readonly="readonly"/>
    <input class="submit" type="submit" value="Submit"/>
</form>
like image 130
lightswitch05 Avatar answered Feb 02 '23 00:02

lightswitch05


Depending on which browsers you're planning to support, you could use the HTML5 required attribute and forego the JS.

<input name="promotioncode" id="promotioncode" type="text" required />

Fiddle.

like image 26
pdoherty926 Avatar answered Feb 01 '23 23:02

pdoherty926