Robbert Robbert -3 years ago 119
Javascript Question

Uncaught TypeError: Cannot read property 'match' of undefined

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

});
}

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download