Uncaught TypeError: Cannot read property 'match' of undefined

53,473
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.

Share:
53,473
Robbert
Author by

Robbert

Developing WordPress websites for 6 years.

Updated on June 15, 2020

Comments

  • Robbert
    Robbert almost 4 years

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