Manoj Singh
Manoj Singh

Reputation: 7707

Getting error while using .Val() in jquery

I am using JQuery and I have got below JQuery Code sample.

JQuery Code:

 $.ajax({  
        type: "POST",
        url: "Login.aspx",  // Send the login info to this page
        data: str,  
        success: function(result)
        {  
             // Show 'Submit' Button
            $('#loginButton').show();

            // Hide Gif Spinning Rotator
            $('#ajaxloading').hide();  

            var resLength = (result).val().trim().length;
            alert(resLength);
            if(resLength!=0)
            {

                var arr = result.split(",");
                var fname = arr[0];
                var lname = arr[1];
                var activeCardNo = arr[2];
                var multipleTier = arr[3];
                var activeStatus = arr[4];
                var access = arr[5];
            }
        }
    }); 

In Above code sample when I am trying to use .val() in below line

var resLength = (result).val().trim().length;

it is giving error "result.val is not a function", If I am using just result.trim().length its working fine in firefox, however giving error in IE.

Please suggest!

Upvotes: 3

Views: 3367

Answers (5)

Kobi
Kobi

Reputation: 137997

try this:

var resLength = $.trim(result).length;

If result is a string, it doesn't have a val function. trim isn't supported cross-browser, so you should use jQuery.trim instead.

Another option is checking the value directly. The empty string has a false value in JavaScript, so you can check:

result = $.trim(result);
if(result)
{
    // split, ...
}

If result is intended to be an element, you should wrap it in a jQuery object:

var resLength = $.trim($(result).val()).length;

Upvotes: 6

qwertymk
qwertymk

Reputation: 35256

It's not a jQuery object, it's just a text value of the returned ajax

Upvotes: 0

kobe
kobe

Reputation: 15835

(result).val(); this is wrong

the above one is used for input type html values

if the result is html please use

.text(); or .html()

Upvotes: 0

Knowledge Craving
Knowledge Craving

Reputation: 7995

The code should be:-

var resLength = result.val().trim().length;
alert(resLength);

Writing "(result)" instead of "result" gives the error. This is because the variable here is the "result" itself.

Hope it helps.

Upvotes: 0

user180100
user180100

Reputation:

The correct syntax is result.trim().length and IE doesn't support trim() (see .trim() in JavaScript not working in IE) so it complains.

Try adding the accepted answer code from he linked question to your code and see if it fixes it.

Upvotes: 0

Related Questions