简体   繁体   中英

How To Check For Empty Fields In HTML Form With JavaScript

I'm checking a website registration form with JavaScript code and onchange listeners. Empty fields/spaces need to be checked for first before checking for illegal characters, too long strings, etc.

I've read this .

But for a null string,

   if (field.value ==="")
      alert("Empty field!");

this will not generate the desired alert.

People at the end of the above thread suggested that recent browser versions might not accept such a statement.

So, how do I sort out empty/blank/ignored fields?

EDIT 1

I've already tried

if (!field.value)  

but it only provides an alert if the user has already typed some characters in the field and immediately deleted them before entering a blank field. It will not provide an alert just by clicking the mouse on it and then tabbing on to the next field. It looks like I may need to assign a null value to these form fields at the outset. . I am using implicit adding of the changeEvent listener, ie on seeing a value explicitly assigned to the onchange attribute of an element, it is activated without any addEventListener(..) statement.

Also,

if (field.value.length == 0) 

does not seem to produce any alert.

EDIT 2

Sorted, I think.

I was using the JavaScript null field check as part of a field-by-field validation check on a web form.

I was using onchange as the event handler. This was wrong. What was needed here was onblur since in the case of a completely null field (ie a field on which nothing had been entered before tabbing away from it), no change has been effected -- and therefore no onchange event occurs that would trigger a JavaScript alert.

Thanks for your efforts.

I was stuck on this one across a couple of weeks and only sorted it with the help of some experimental programming by a more experienced guy at work here.

In this script you can see an alert of your variable value ( a console.log would be lees noisy:) The use of === is for type check but in your example does not make sense as you are using an empty string

<script>
 var field= {};
 checkEquality(field);
 field.value = "";
 checkEquality(field);

 function checkEquality(object){
  alert(object.value);
  if (object.value === "")
  {
    alert("===");
  }
  if(object.value == ""){
    alert("==");
  }
}

You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (.(!(variable))) in javascript and jquery.

function myFunction() {
    var data;  //The Values can be like as null, blank, undefined, zero you can test

    if(!(!(data)))
    {
        alert("data "+data);
    } 
    else 
    {
        alert("data is "+data);
    }
}

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