Question

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

Uncaught TypeError: Cannot read property 'match' of undefined

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;
            }

        });
    }
Was it helpful?

Solution

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.

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top