Saturday, April 21, 2012

HTML <button> vs <input type="button">

<form name="frmTestingButtonTypes">
 <button>This is a button</button><br />
 <!-- Vs. -->
 <input type="button" value="This is a button">
</form>

HTML allows a developer to use JavaScripts to run custom functions and calculations in a simple, universal web interface.  This can be accomplished with only a little bit of experience with JavaScripting (and with some excellent guidance from w3schools.com).

A problem I ran into recently (having plenty of HTML experience, and stolen only enough JavaScript code over the years to hack through and get by) was with some scuba calculators I recently began developing as HTML forms like this one:

JavaScript scuba calculator utilizing onUpdate events

I decided to omit a submit/command button and instead use onUpdate events to call the calculations so a user can convert from depth to pressure, or change the pressure and convert back to depth.  Also, this way is just cooler.

The problem is that by adding name attributes in a <button> element inside of a <form>, the web page will want to reference any text boxes/drop down menus/check boxes/command buttons/etc. explicitly; so it will pass their values to the URL when any of those elements are applied:

<form name="frmTestingButtonTypes">
 <button name="testButton">This is a button</button><br />
 <!-- Vs. -->
 <input name="testInput" type="button" value="This is a button">
</form>

Original URL remains the same when using onChange events

Including a <button> tag passes control values as arguments to the URL
when the first button is clicked

Clicking the second button passes its value to the URL


The URL examples above return two buttons would continue further if additional controls (text boxes/check boxes, etc.) on the page were populated with data.  Further, this has "navigated away" from the original blank version of the page which may require a user to click the browser's Back button to reset properly.

Instead, use only the latter input tag method
<input type="button" onClick="someFunction()" />
and avoid using the button tags
<button onclick="someFunction()">Name</button>so the arguments will not be passed to the URL.

Additionally, avoid using the type="sumbit" in an <input> tag, which will give the same results as using <button> tags:
<input type="submit" onClick="someFunction()" />