J. Doe J. Doe - 6 months ago 11
jQuery Question

jQuery code conflicting with submit buttons

I have this code on my website:

$('input[type="submit"], a').not('[target=_blank]').click(function(){
var bad = this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0;
if(!bad) {
$(".load-overlay").show();
return true;
}
return true;
});


This is supposed to show a loading screen on valid links; valid links are links without javascript in the href, or with # in the href. Also valid links are without target=_blank attributes.

It's doing its job but it's conflicting with the submits buttons.

The loading screen (
.load-overlay
) doesn't show on submit buttons, but it's defined in the code. What's the matter with this? I have no errors in the console.

Answer

It's because an input does not have a href attribute. Because of that a TypeError Exception will be thrown, when clicking on a submit button. You have to check, if this.href exists, before using it.

change

var bad = this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0;

to

var bad = typeof this.href !== "undefined" && (this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0);
Comments