jQuery: Binding Submit on a Form’s Action Attribute

Sigh… got bit a little today trying to do something with jQuery. I just could not for the life of me understand it! I was wanting to bind a submit handler to a form and, in trying to be clever, thought I would bind the form based on it’s action versus adding an id to it for the sole reason to bind it. So, I tried the following:

$("form[@action='test.php']").submit(function(event){
	event.preventDefault();
	alert("intercepted!");
});

Dang it! For reasons that confound me, it wouldn’t work!

So I took a quick gander at the documentation on the CSS selectors used in jQuery and decided to use the * modifier so it would match if it found it at all:

$("form[@action*='test.php']").submit(function(event){
	event.preventDefault();
	alert("intercepted! " + this.action);
});

For good measure, I thought I’d alert this.action to see the actual value of the action attribute. Surprisingly, it did have the full URL prepended before it… and that’s why I couldn’t bind by it before. LIkewise, I could also use ?= rather than *= if I want to match only the end of the action attribute’s value… since *= will search within the entire string. Good item to know. ;)

  • http://brettic.us Brett Millett

    I just needed that precious event.preventDefault() nugget. Thanks!