Lucky Soni Lucky Soni - 6 months ago 31
Javascript Question

text input value greater than.. jQuery

I am using wordpress and trying to throw a message when the value for a text input is greater than 40..

<input type="text" name="quantity" size="2" value="<?php echo wpsc_cart_item_quantity(); ?>" />


Now i want to throw a message (alert) when this text field contains value greater than 40 and also want to reset its value to ''
My wordpress theme uses jquery 1.71
I am doing the following:

jQuery("input[type='text'][name='quantity']").change(function() {
if (this.val >= 41) {
alert("To order quantity greater than 40 please use the contact form.");
this.val == '';
this.focus();
return false;
}
});


Thanks.​

Answer

You need in first place to wrap this with the $ function, since this is the DOM element returned by the selection query and not a jQuery object, and the val() function is not available on that kind of object.

Also, you need to call the val() function with parenthesis, otherwise you're working on the body of the function, not the value it returns.

Finally, there is a typo on the assignment statement. You should at least do this.val = '', but that won't work since val is a function, not a variable. Working code should look like this:

$("input[type='text'][name='quantity']").change(function() {
    if ($(this).val() >= 41) {
        alert("To order quantity greater than 40 please use the contact form.");
        $(this).val('');
        $(this).focus();
    }        
});    
Comments