JS Form Buttons Reliability

On the project I’m on, I’ve run into a number of problems getting various types of button to run JavaScript and not submit the form they’re on. My conclusion:

The most reliable way to have buttons that run JavaScript instead of submitting the form they’re on, is to use <input type=”button”/>.

The other options are <input type=”submit”/>, <button/>, and <button type=”submit”/>. But all of these have their issues.

Theoretically, <button/> should also not submit the form you’re on. It works that way in IE6, 7, and 8, but in FF3 it does submit the form you’re on.

There are ways you should be able to disable form submission when JavaScript is running. Theoretically, any “onsubmit” handler that returns false should prevent the form from being submitted. I wasn’t able to get this to work by using YUI.util.Event.addListener, but I was able to get it to work fairly reliably by using formNode.onsubmit = function() { return false; }. However, this started working only sporadically in IE8.

Since the project I’m on requires JavaScript, the most reliable way I found is to change all the buttons to <input type=”button”/>. There may be something more complicated going on that could be worked-around, but this way seems to be the least likely to cause future problems.

If your project needs to work with or without JavaScript enabled, here’s what I’d recommend. Code the page to use <input type=”submit”/>. Then, when your JavaScript init runs, change the type attribute to “button,” and attach your click listeners.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: