J. Doe J. Doe - 1 year ago 48
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) {
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 (
) 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 Source

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.


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


var bad = typeof this.href !== "undefined" && (this.href.lastIndexOf('#') >= 0 || this.href.indexOf('javascript') >= 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download