OnBlur Assignment to Function in Javascript
I have a code like this;
<script type="text/javascript">
var ID= document.getElementById('customfield_10033');
var IDNumber= document.getElementById('customfield_10033').value;
ID.onblur=function(IDNumber)
{
if ((IDNumber!="") && (IDNumber.length!=11)){
alert("Your ID number should 11 digits.");
}
But when i enter ID number with 11 digits, shows me alert function. But it shouldn't.
I think i doing wrong assign Onblur prope开发者_Go百科rty to function.. ID.onblur=function(IDNumber)
How can i fix this code?
You define IDNumber
when you assign the event handler (so it will probably be holding whatever you set the default value of the field to be), but you almost certainly want to define it when the blur event occurs.
Move
var IDNumber= document.getElementById('customfield_10033').value;
Inside your event handler function.
(Since you already have a reference to the element it would be more efficient to do var IDNumber = ID.value;
too)
You should have something like this instead:
ID.onblur = function(IDNumber)
{
var IDNumber = ID.value;
if (IDNumber !== "" && IDNumber.length !== 11)
{
alert("Your ID number should 11 digits.");
}
}
By assigning the value
into variable, you place static data, not a pointer to the value so you have to read the "live" value every time.
You forgot to close the if-statement. Try this:
if ((IDNumber!="") && (IDNumber.length!=11)) {
alert("Your ID number should 11 digits.");
}
Regards, Thomas
精彩评论