简体   繁体   中英

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 property 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

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