3

I have a textbox and need to be validated after onblur() event. There should be error message, if and only if the textbox is empty else no message is displayed on webpage. But I think if part of the javascript is executing each time.

<input placeholder="First Name" type="text" name="fname" onblur="validatefname()">

Javascript function

function validatefname(){
    var fn=document.getElementsByName("fname").value;
    if(fn==null || fn==""){
        document.getElementById("bubble").style.visibility="visible";
        return false;
    }
    else{
        document.getElementById("bubble").style.visibility="hidden";
        return true;
    }
}

Please let me know what went wrong here?

dimo414
  • 47,227
  • 18
  • 148
  • 244
SanTech
  • 128
  • 2
  • 14

2 Answers2

5

getElements by name, returns a set of DOM elements, so you need

var fn=document.getElementsByName("fname")[0].value;
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • Great solution! Can you please explain what is DOM and use of [0]. – SanTech Jun 07 '15 at 17:26
  • 1
    @SantoshTeurwadkar DOM is Document Object Model, which is the convention for interacting with elements on a webpage, which are called DOM elements. The method `getElementsByName` returns a set, which is an array-like structure containing DOM nodes. The *array-like* part is what lets you use `[0]` to access the element. See here for info on DOM sets: http://stackoverflow.com/questions/28163033/when-is-nodelist-live-and-when-is-it-static/28163742#28163742 and here for info on DOM: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model – chiliNUT Jun 07 '15 at 18:17
1

You can pass the input element in the validation function as follows:

<input placeholder="First Name" type="text" name="fname" onblur="validatefname(this)">

And access the same inside your validate function as below

function validatefname(elem){ 
 var fn=elem.value; 
 if(fn==null||fn=="")
 { 
   document.getElementById("bubble").style.visibility="visible"; 
   return false; 
  } 
  else{ 
   document.getElementById("bubble").style.visibility="hidden";
    return true; 
  }
}

Now if you keep your text box empty then it will display the bubble element else not.

debatanu
  • 766
  • 5
  • 11