未捕获的TypeError:无法读取未定义的属性“匹配”

时间:2020-12-27 20:34:07

with this piece of jQuery I check if some fields are match or are not empty, but I get this error.

使用这段jQuery,我检查一些字段是否匹配或不为空,但我收到此错误。

Uncaught TypeError: Cannot read property 'match' of undefined

未捕获的TypeError:无法读取未定义的属性“匹配”

Can anyone tell me what I am doing wrong here?

谁能告诉我这里我做错了什么?

if ( width.match( /^\d+$/ ) && height.match( /^\d+$/ ) && type.length > 0 && color.length > 0 ) {

This is the full code:

这是完整的代码:

if( $( "#config" ) ) {
        $( 'input, select' ).on( 'change', function(){
            var width   = $( "#config-steps #width" ).val();
            var height  = $( "#config-steps #height" ).val();
            var type    = $( "#config-steps #type" ).val();
            var color   = $( "#config-steps #selected-color" ).val();

            if ( width.match( /^\d+$/ ) && height.match( /^\d+$/ ) && type.length > 0 && color.length > 0 ) {
                $( "#checkout-message" ).show();

                // Change visible price 
                $( "#change-price" ).html( calculate_price().toFixed( 2 ) );

            } else {
                return false;
            }

        });
    }

1 个解决方案

#1


6  

if( $( "#config" ) ) {

is always going to be true with jQuery since jQuery returns an object and objects are truthy. The check should be checking the length which will return a number and zero is false.

jQuery总是如此,因为jQuery返回一个对象,对象是真实的。检查应检查将返回数字的长度,零为假。

if ($("#config").length) {

Now when jQuery does not find an element, than val() will return undefined, so it is not finding the element.

现在当jQuery找不到元素时,val()将返回undefined,因此它找不到元素。

#1


6  

if( $( "#config" ) ) {

is always going to be true with jQuery since jQuery returns an object and objects are truthy. The check should be checking the length which will return a number and zero is false.

jQuery总是如此,因为jQuery返回一个对象,对象是真实的。检查应检查将返回数字的长度,零为假。

if ($("#config").length) {

Now when jQuery does not find an element, than val() will return undefined, so it is not finding the element.

现在当jQuery找不到元素时,val()将返回undefined,因此它找不到元素。