text input value greater than.. jQuery

2019-06-14 13:10发布

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.​

2条回答
We Are One
2楼-- · 2019-06-14 13:50

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();
    }        
});    
查看更多
Rolldiameter
3楼-- · 2019-06-14 13:51

Well, you were nearly there, use:

jQuery("input[type='text'][name='quantity']").change(function() {
    if (parseInt($(this).val(),10) > 40) {
        alert("To order quantity greater than 40 please use the contact form.");
        this.value == '';
        /* or with jQuery: $(this).val(''); */
        $(this).focus();
        return false;
    }
});

References:

查看更多
登录 后发表回答