简体   繁体   中英

JavaScript variable is undefined after being passed in a function

Hi I am working with a function and I just can't see what the problem is, help please?

This is the JavaScript function to check the length of an input.

function checkLength(o, min, max)
    {
        if ( o.val().length > max || o.val().length < min )
        {
            $("#uper_length_stud").show()
            return false;
        } 
        else
        {
            return true;
        }
    }

under it is a code which calls it.

$("#signin").click(function(e) {
       var name = $("#up_stud_fname").val(), x;
       x = checkLength(name, 3, 50);
       //other codes follow
}

It says at part o.val() that o is undefined. Though I think it is passed correctly? What seems to be the problem?

The Html part Update 更新

In checkLength() you have not passed any thing.

Try to pass all arguments to it

pass three parameters to the function

Here function wants 3 parameters ,and you are not passing it,so It says undefined

o, min, max

Try this One Check this fiddle http://jsfiddle.net/pratbhoir/9QTYk/

Html Code

<input id='firstName' />
<button id="btn"> Button</button>

JavaScript Code

$("#btn").click(function() {
    var name = $('#firstName').val();
    x = checkLength(name,1,4);
    //other codes follow
});


function checkLength(o, min, max)
{
    if ( o.length > max || o.length < min )
    {
        //$("#uper_length_stud").show()
        return false;
    } 
    else
    {
        return true;
    }
}

You can takeout the .val() from your if condition because name is a string which you are passing:

function checkLength(o, min, max){
    if ( o.length > max || o.length < min ){
        $("#uper_length_stud").show();
        return false;
    } 
}

and i think you don't need the else part and make sure that your function is in global scope.

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