jdog123 jdog123 - 1 year ago 129
Javascript Question

Comparing String to null or empty values in JavaScript

i am trying to create an if and else statement in JavaScript wherein if the string is empty, it will send out an alert box that all forms must be filled up. If not, the data grid in the webpage will increment with all the information entered on the form. But it seems that my code is not working properly. Below is my javascript code

function addData(){
if(document.getElementById("txt_description").isEmpty || document.getElementById("txt_update").isEmpty){
alert("Missing information!!! Please fill up all the blank items");
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);

cell1.innerHTML = document.getElementById("input_name").value;
cell2.innerHTML = document.getElementById("input_blank2").value;
cell3.innerHTML = document.getElementById("txt_description").value;
cell4.innerHTML = document.getElementById("input_status").value;
cell5.innerHTML = document.getElementById("input_pageable").value;
cell6.innerHTML = document.getElementById("txt_update").value;


Answer Source

Change your if statement to this:

if(document.getElementById("txt_description").value == ""|| document.getElementById("txt_update").value == "")

.isEmpty does not exist in javascript! If your input is empty, comparing it to an empty string will be sufficient!

For dealing with null values:

if(document.getElementById("txt_description").value == ""|| 
document.getElementById("txt_update").value == "" || 
document.getElementById("txt_description").value == null || 
document.getElementById("txt_update").value == null)


As mentioned in one of the comments, .value cannot be null. So you cold simply use the following if statement:

if(document.getElementById("txt_description").value == ""|| 
    document.getElementById("txt_update").value == "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download