I sincerely hate Internet Explorer sometimes. I never like it. Today it really pissed me off. If you use multiple <button> tags in one form, think again. It doesn't work in IE like it should do [...in Firefox]. If you have a form like this:


<form action="showRequestVariables">
<button type="submit" name="button1">Button1</button>
<button type="submit" name="button2">Button2</button>
</form>

Then, which ever button you press you'll get these request variables if you use Internet Explorer:


button1 = "Button1"
button2 = "Button2"

In Firefox you only get one; the one you pressed. Doesn't that seem logical? The Firfox way I mean.

To solve the problem and tame the IE bastard you'll have to loose the <button> tag and go for a <input> tag instead:


<form action="showRequestVariables">
<input type="submit" name="button1" value="Button1" />
<input type="submit" name="button2" value="Button2" />
</form>

Then you get the more sane behaviour you'd expect from a web browser.

Disclaimer: The spec (is too long to read) could prove me wrong but I feel pretty confident that Firefox has got it more right in this instance.

Comments

Page 1 of 2

Post your own comment
Peter Bencsik

IE makes you suck again. I have the same problem with it. I have a form with multiple <button>some text</button> tags, like this:
In-silico research (<button type="submit" name="removemethod" id="removemethod" value="3">-</button>),...
In Firefox if I press the button, I get these post values:
removemethod=3
In IE:
removemethod=-
So it always send the text between the <button></button> and not the value.

Peter Bengtsson

Exactly. Perhaps it's not IE's fault but the <button> tag's fault. Either way, it can't be used.

Patrik Granlöv

The VALUE should always be the value submitted with the form. But IE submits the button text and ignores VALUE. So once again IE has it wrong.

Anonymous

button is not a form tag that's why submitted value is inconsistant. If you need to have a form (submitting values), you should be using input type=button.

Anonymous

Nothing in the HTML4/5 standard says elements that are not form elements can behave just how the browser wants.

ma.pelletier

there is no such thing as <button type="submit"> the thing you're looking for is <input type="submit">

Brandito Designs

actually it's just <button>, type="reset" is an option but type="submit" is a <button> elements default.

Peter Bencsik

Check this:
http://lists.evolt.org/archive/Week-of-Mon-20001002/017911.html

The funny (and most annoying) is that IE always sends the button, even if it was not pressed. In my example, I always gt removemethod=-, even if I press the normal submit button in the form.

BulletProofPoet

Thanks for posting this. I thought I was going mad when I saw this behaviour this afternoon. Unfortunately, it took me a couple of hours to disgnose the problems and find this page though!

There's no way IE should post the button field at all if the button wasn't pressed. Just another reason why IE should be taken out and shot!

AngryWithIE

I was going mad as well. So how am I supposed to get a button with text and an image if I can't use the <button> element?

Peter Bengtsson

You can but not collect the correct value. If you just want a button that submits the form, the <button> will do fine.

Chris Hutchins

They are out to drive me insane - with Moz/NS/Firefox I can get a simple button with an image of my choice (I use it for a photo browsing page). I have yet to come up with even a difficult work-around in IE.

Newbie Cobbler

Anybody know if its the case that Firefox does NOT support button/input border attributes - eg., border-left:5 solid#000099 and border-right:5 solid#000099 and similarly top/bottom - IE supports these OK - is there another way of naming these to get same result in Firefox/Netscape such that It will come up in IE as well?

Solange

you need write
eg. border-left:5px solid #000099;

look "5px" and not "5"

Meyaline

>
> Disclaimer: The spec (is too long to
> read) could prove me wrong but I feel
> pretty confident that Firefox has got
> it more right in this instance.
>

The W3C HTML 4.01 specification (1999) says (http://www.w3.org/TR/html4/interact/forms.html#h-17.13.2): "If a form contains more than one submit button, only the activated submit button is successful." (and by submit button, they mean both "<input type="submit" ... />" and "<button type="submit" ...>...</button>", as said here: http://www.w3.org/TR/html4/interact/forms.html#buttons)

It also is in the working draft of HTML 4 (1997)... (maybe a bit less clear, as they only say so for "<input type="submit" ... />", and say the "button" element works pretty much the same -well, not that unclear, AFAIC)

Anyway, I do wonder how it is of any use, to send the name/value of every submit buttons... Yet another proof that Microsoft just want to screw the world...

Heck, they are members and contributors of the W3C (and took part in the developpment of the HTML specifications), one would expect they at least properly implement such basic rules... well, they don't even do that... (and the worst is that it is purely intented)

Why in the world did I choose to become a webmaster...? :/

Random Penguin

THE SOLUTION TO THE IE BUTTON TAG DISPLAY VALUE/TEXT PROBLEM !!!!

Hi folks,
Here is a solution that works in IE.
I recommend using JavaScript or server-side code to detect the browser, since this code will not work in non-JavaScript browsers, whereas <button> code will.

<input type=submit name="buttonName" value="buttonValue" onclick="this.style='display: hidden';this.value='buttonValue'; this.submit()">

infinite

using that javascript method that "Random Penguin" provided is kinda silly .. buttons disappearing when clicked .. no thanks ..
i had the same problem between IE and FF, <input type=image name=button value=something> FF will sucessfully create a POST variable named 'button' with the value 'something' with 'button.x' and 'buttin.y' while IE only creates the last two ... so i had to switch to the button tag for my image button ... and like mentioned here i had the same probelm .. IE will assume the value of whatever inside the tag and ignore the "value" attribute ... so the simplest solution that comes to mind is setting the text size to 0px using css .. this way both browsers will work and everybody will be happy ... however it's all IE's fault ... i hate that damn thing but as a web developer i have to bend my self in it's favour cuz it's the most used browser out there .. personally i think anybody using it is a damn moron ...

Chris

Another solution is to disable all other submit button in the onClick Event.
But you know, it is all a workaround ...

Chris

For those who are interested:

function disableOtherSubmitButtons(submitButton)
{
if(!submitButton)
{
alert("no object found");
return;
}

if(!submitButton.type)
{
alert("no type attribute");
return;
}

if(submitButton.type != "submit")
{
alert("no submit button");
return;
}

if(!submitButton.form)
{
alert("parentless button (no form)");
return;
}

var formElements = submitButton.form.elements;

for(var i=0; i<formElements.length; i++)
{
//leave the pressed button as is...
if(formElements[i] == submitButton)
continue;

//disable all other submit buttons
if(formElements[i].type == "submit")
{
formElements[i].disabled = "true";
}
}
}

How to use it:
<form action="showRequestVariables">
<button type="submit" name="button1" onClick="disableOtherSubmitButtons(this)">Button1</button>
<button type="submit" name="button2" onClick="disableOtherSubmitButtons(this)">Button2</button>
</form>

Aaron Evans

Yeah, you can disable the other submit buttons, but it still submits the text within the button element, not the text of the value attribute!

This is a real pain because I am trying to determine an "action" based on the value attribute and I might want to reuse the text for different "actions" on different pages but posting to the same "action handler".

Marc Pujol

I've ended using a bunch of tricks wich finally worked pretty well:

1. We will run some javascript only if our browser is IE 5.5>, so we'll add this to header:

<!--[if gte IE 5.5000]>
<script type="text/javascript" src="btnfix.js"></script>
<![endif]-->

2. We'll allways assign the same value to the "class" and "value" tags of the button:

<button name="action" value="add" class="add">
<img src="add.gif" alt="add value" />Add to cart
</button>

3. We'll add this code to the "btnfix.js" file, so that it'll run on window.onload():

window.onload = function() {
var btns = document.getElementsByTagName('button');
for(var i=0;i<btns.length;i++) {
btns[i].onclick = function() {
var bs = document.getElementsByTagName('button');
for (var i=0;i<btns.length;i++) {
if (btns[i] != this)
btns[i].disabled = true;
}
this.innerHTML = this.className;
return true;
}
}
}

Marc Pujol

There's a typo in the script, where line 5 says: "var bs = ..." it should be "var btns = ..."

With all this we end up having fully functional buttons in IE and any other browser (that handles buttons correctly, like all gecko/khtml based ones). The only counterpart (and only in IE) is that our button will "unrender" itself just before sending the form (when our script changes it's innerHTML so it sends the correct value)

Tom

I found another possible solution for the problem:
Encapsulate every button in its own form. So instead of
<form action="showRequestVariables">
<button type="submit" name="button1">Button1</button>
<button type="submit" name="button2">Button2</button>
</form>

you write

<form action="showRequestVariables">
<button type="submit" name="button1">Button1</button>
</form>
<form action="showRequestVariables">
<button type="submit" name="button2">Button2</button>
</form>

IE now posts the correct values (at least that worked for me).

Jon Haugsand

Tom's solution is problematic when you have a table where each row have a submit button, and the other rows may or may not have input fields.

This should be quite common.

- Jon

Chris Doors

Yes this is blooming annoying;
Here's what I did;

I pairred each button tag with a hidden input field in the following way:

<button onClick='buttonTagClicked(this.name)' type='Submit' name='something1~button'>Submit</button>
<input type=hidden id=something1 name=something1 value=0>';

<button onClick='buttonTagClicked(this.name)' type='Submit' name='something2~button'>Submit2</button>
<input type=hidden id=something2 name=something1 value=0>';

And wrote this javascript function:

<script language="JavaScript" type="text/javascript">

function buttonTagClicked(field)
{
var fieldsarray=field.split("~");

document.getElementById(fieldsarray[0]).value=1;
}
</script>

Then when the button is submited it updates the related hidden field to 1. You can then use the hidden field variables to find which button tag was pressed as it will have value of 1.

We should not have to do this but IE is obviously cr*p. Hope this helps

Peter Bengtsson

That's a very complex solution. Is there a reason for this example that you haven't used any of the functionality of <button> tag over a <input type="submit" one?

Chris Doors

I removed all the images and such from between my button tags as would have made comment too large and ugly. If I didn't want all the button tag's functionality then I would have used the input tag as you suggest. Hope my code helps a bit.

Robert Polomsky

Hmm, quite nice, Chris. I will try it.
I had another solution. Better code, but it redraw button for a moment between clicking and disappearing of old page. Maybe somebody could improve it.

function submitForm() {
var e = document.getElementById('btnAction0');
e.value = e.attributes['value'].value;
}

<form method="get" action="login.cgi" onsubmit="submitForm()">
<button type="submit" id="btnAction0" name="action" value="login">Login me</button>
</form>

( be sure you don't use function name: "submit()" )

Chris Doors

I have cleaned up my code in previous example.

This is used if you have multiple button tags submitting the same form, so you can tell which button has submited form.

<form method="POST">
<input type=hidden id="submitbuttonpressedvalue" name="submitbuttonpressedvalue">

<button type="submit" onClick='buttonTagClicked(this.realvalue)' name='continuebutton' realvalue='continue'><img src="whatever.gif"></button>
<button type="submit" onClick='buttonTagClicked(this.realvalue)' name='backbutton' realvalue='back'><img src="whatever.gif"></button>
</form>
<script language="JavaScript" type="text/javascript">

function buttonTagClicked(buttonvalue)
{

document.getElementById('submitbuttonpressedvalue').value=buttonvalue;
}

</script>

Now in the post vars the realvalue of the button pressed should be in the
'submitbuttonpressedvalue' post var.

I think that's correct

Richard Williams

I'm rather late finding this problem. Chris' solution works fine for IE6 etc. but fails for FireFox. I have both value=".." and realvalue=".." Then in my PHP script I test for submitbuttonpressedvalue="undefined" when I know it's not IE and get the proper POST variable value otherwise I use the submitbuttonpressedvalue.

FataL

IE 7 beta 2 solved that problem that submit all buttons by pressing one.
BUT there STILL one more poblem: IE 7 beta 2 still submit innerHTML of BUTTON instead of value attribute. :-/ DAMN!
BTW, try Dean's Edwards IE7 lib - it's solve all this issues:
http://dean.edwards.name/IE7/

Rich

I just got bit by this bug today, took me a while to figure out what was going on. I was using <button> for precisely the reason that it lets you set a different label ("Edit Foo") from its value ("edit-<foo's id>").

My solution was this bit of javascript:

function submitAndRedirect(submitButtonID, redirectCode) {
        var submitButton = document.getElementById(submitButtonID);
        var redirectElementID = "input_submit_redirect_" + submitButton.form.id;
        if (document.getElementById(redirectElementID)) {
                document.getElementById(redirectElementID).value = redirectCode;
        } else {
                element = document.createElement("input");
                element.name = "submit_redirect";
                element.id = redirectElementID;
                element.type = "hidden";
                element.value = redirectCode;

                submitButton.form.appendChild(element);
        }
}

Then changed the <button> code to:

<input type="submit" id="button_99_edit" name="submit" value="Edit Foo" onclick="submitAndRedirect('button_99_edit', 'edit-99')"/>

It creates a hidden form item that my server-side code can look for, and gives it the value 'edit-99'.

I *would* add this to my list of items I'm praying Microsoft fixes in IE 7, but I don't think there's room left. It's already so big.

Peter Bengtsson

Shame it doesn't work without javascript though.

You could make it much simpler if you'd just write you input tag like this:

<input type="submit"
name="99"
value="Edit this"
onclick="this.value=this.name;this.name='idvalue'"
/>

...or I just don't understand your particular application problem.

Rich

I didn't want the user to see the name of the button suddenly change to a piece of code the moment it's clicked on. My solution involves a longer bit of javascript, but it's a one-time cost since every page that uses just links to a site-wide .js file, and the in-button portion is pretty simple. Plus it's completely transparent to the user.

I've made a slight change to it, in that the button HTML code is now:

<input type="submit" id="button_99_edit" name="submit" value="Edit Foo" onclick="submitAndRedirect(this.id, 'edit-99')"/>

(Replaced hard-coded ID with this.id)

Daniel Danopia

Just pass 'this' and then you don't have to do an ID lookup.

Jeff

Thank you for this solution. This has had me stumped for a few days. I think I still have a few hairs left that didn't get pulled out.

Dromyl

hey guys,
when i use <button> in FF with my ASP.Net App. The page is getting unecessarily refreshed.
where as it works fine with IE.

I have numbers of <button> tag in my page, i mean they are getting created dynamically.

Coz m using the btn tag just 2 call a javascript so i dont want page to be refreshed.

Any Comments/workarounds.

Jyoti

You can add attribute type="button" inside the button tag, then ur problem could be solved.

srbardo

I`m another annoyed web developer who whas about to going mad due to Microsoft incompetents, getting the same problems as you with multiple input and button values submits.

I think i´ll use the id property as it was the value property, plus hidden inputs and JavaScript code.

Thx for the info and up the FireFox!

Joerg

The really annoying this is: Why didn't M$ fix this bug in IE6 two years ago in one of its countless Windows updates?

I "solved" the problem by using simple <input> buttons instead of <button> buttons.

Anonymous

Add me to the list. MS implementation causes the use of button to be useless. Using the button element allows us to have a label independent of the value attribute.

And you can't create standards-compliant table-filled forms with IE's implementation of button.

VERY PO'D

stereopixel

I needed this for image buttons.

My version of it, which I think is simple and effective (thanks to all the previous contributors) but needs javascript:

function imgClick(value)
{
document.getElementById('IEfix').value = value;
}

<form method="post" action="ACTION.PHP">

<input type='hidden' id='IEfix' name='imageButtonIE' value=''>

<input type='image' src='1.jpg' value='IMG1' name='imageButton' onClick='imgClick(this.value)' />
<input type='image' src='2.jpg' value='IMG2' name='imageButton' onClick='imgClick(this.value)' />
<input type='image' src='3.jpg' value='IMG3' name='imageButton' onClick='imgClick(this.value)' />
<input type='image' src='4.jpg' value='IMG4' name='imageButton' onClick='imgClick(this.value)' />
<input type='image' src='5.jpg' value='IMG5' name='imageButton' onClick='imgClick(this.value)' />

</form>

--------------------------

No need to specify a different name for each image, you get 'imageButton' = value on Firefox, and 'imageButton' = "" on IE.

Then if you check 'imageButtonIE' you get the codename value of the clicked image (you can put there the name, or the index...)

snipes

stereopixel's script doesn't work with the <button> tag. If you try to get the set value for the button with 'this.value' IE will still send the innerHTML from the button tag.

I solved it by using the button tags name as the value instead and then accessing the value with 'this.name'. The server then requests the value from a hidden <input> with a specific name...

cresus

After reading all the page, it seems to me it is the best solution to this awful bug...

We only want to bypass a bug from IE, and we surely don't want to overload our codes because of it. stereopixel's solution corrected by snipes is quick and keeps everything relatively simple, clean and tidy.

Thanx everybody for your contribution, it helped me a lot ;-)

dada

this is a fantastic solution - thanks

COLOSSUS

Yes, this solution was my salvation, too. :)

Thank you very much!

Paul

I had this problem today when i was using a php variable as the value using the <input> tag and sending it to another page using GET to be used for a MySQL query. It worked fine in FF but IE didnt want to know.

heres the code...

<input type="image" class="link" src="../viewgallery.gif" name="galname" value="'.$gallery_name.'" />

Thanks to this page giving me some ideas,

All i did was add this line to get it to work in IE...didnt need any javascript!

<input type=hidden id="galname" name="galname" value="'.$gallery_name.'">
</form>

Jesse

I didn't get Pauls solution to work with multiple buttons, but here is my solution without javascript (uses php instead):
<input type='image' alt='img1' src='../images/img1.gif' name='img1' />
<input type='image' alt='img2' src='../images/img2.gif' name='img2' />

and to see which button the user clicked:
if (isset($_POST['img1_x'])) {
unset($_POST['img1_x'],$_POST['img2_y']);
/* do whatever you wan't */
}
else if (isset($_POST['img2_x'])) {
unset($_POST['img2_x'],$_POST['img2_y']);
/* again do whatever you wan't */
}

I have to unset the post values because the user can click first img1 then img2 then again img1 and i just simply sen the whole $_POST array so eventually it would contain both. And still don't get different values, but can play with the different names.

If anyone can make a simpler solution with php i'd be happy to here about it

Keith Lawler

This is terrific! Thank you Jesse! I just used this solution and added the ability to get a value too. What you can do is add the value to the end of the name attribute seperated by a dash. For example if your name is "imagePressed" the new name would be "imagePressed-3". Then call the below function to extract it out.

<input type='image' name='imagePressed-3' src='/btn.gif'>

function getImageButtonValue($formvars, $name) {
// loop through the keys
foreach ($formvars as $key => $value) {
// if key is what you are looking for
if (strstr($key, $name)) {
// extract out the value from the name
$temp = split('-', $key);
// get rid of the _x or _y too
$temp = split('_', $temp[(sizeof($temp)-1)]);
return $temp[0];
}
}
// didn't find anything so return false.
return false;
}

Just becareful if your name attribute or value has dashes or underscores.

Hope this helps!

Rich LaMarche

Here is another variation.

<button type="submit" name="btnContinue" onclick="this.setAttribute('value','continue');"><img src="whatever.gif"></button>
<button type="submit" name="btnBack" onclick="this.setAttribute('value','back');"><img src="whatever.gif"></button>

Doesn't require a hidden field.

Ralph Holz

I find that Rich LaMarche's solution is not yet perfect. E.g. in IE6 - may it burn in hell - it does not work if you want to use two buttons with the same name. Example:

<button name="choice" type="submit" value="submitLogin" onClick="this.setAttribute('value', 'submitLogin');">1</button>

<button name="choice" type="submit" value="submitCancel" onClick="this.setAttribute('value', 'submitCancel');">2</button>

I use a MVC architecture and "choice" is the variable that I use to determine which step to take next. If you try to do it as above, even with Rich's patch, IE6 will still overwrite "choice" with the innerHTML of the second button ("2"), and that will be the value of "choice".

However, the following works: change the name attribute to something else, e.g. "choiceV". Then:

<button name="choiceV" type="submit" value="submitLogin" onClick="this.setAttribute('value', 'submitLogin'); this.setAttribute('name', 'choice');">...</button>

<button name="choiceV" type="submit" value="submitCancel" onClick="this.setAttribute('value', 'submitLogin'); this.setAttribute('name', 'choice');">...</button>

This takes care that only one button will be sent with name "choice", the other one will remain "choiceV", and your controller can use "choice" to properly determine the action to be taken. It does add a short delay to the processing of the page, but does not need JavaScript. Firefox can handle it as well. I dislike such patches immensely, but here I have no choice... but I will add the "Spread Firefox" button to my homepage now.

Arkady Renko

Guys, an enormous thank you for writing about the messed up nature of IE's button support. I spent hours on a problem assuming it was something to do with the way i'd set my sessions.. when it turns out that quite simply IE was sending the wrong value to my session variable. You've just saved me more hours of heartache

Cheers

Anonymous

tada!
this work !!!

button.endsWith("Seguir")

<button type="submit" name="button" value="Seguir"><img src="images2/right-blue.gif"> Seguir</button>

Sina Salek

Hi, thanks for all the solutions,
I like Ralph Holz solution, i think it's useful and easy so i improved it to a general way with no extra code require. only one function which works only in IE. it will change name of the button tags to something unique for preventing duplication. and then adds a js codes to each button onClick attribute. this event function is able to fetch value of button via regex and add hidden field with that value before submitting form.
hope it helps...

<script type="text/javascript">
//--(Begin)-->fetch value of button via outerHTML
function getButtonTagValue(buttonObj) {
var regexObj = /<[^<]*value="([^"'<>]*)"[^>]*>/;
//'
var match = regexObj.exec(buttonObj.outerHTML);
if (match != null && match.length > 1) {
return match[1];
} else {
return '';
}
}
//--(End)-->fetch value of button via outerHTML

function insertHiddenField(parentObj, name, value) {
var hiddenField = document.createElement('input');
hiddenField.type='hidden';
hiddenField.name=name;
hiddenField.value=value;
parentObj.parentNode.appendChild(hiddenField);
}

function fixIeButtonTagBug(formId) {
if (document.all || 1==1) {
var baseObject=document;
var elms;
var custFunc;

if (formId) baseObject=document.getElementById(formId);
elms=baseObject.getElementsByTagName('button');

if (elms) {
for (var x=0; x<elms.length; x++)
if (elms[x].tagName=='BUTTON') {
//this.setAttribute('value', getButtonTagValue(this)); this.setAttribute('name', '"+elms[x].name+"');
custFunc=new Function(
"insertHiddenField(this,'"+elms[x].name+"',getButtonTagValue(this));"+
"return true;"
);

elms[x].onclick=custFunc;
elms[x].name='___fixIeButtonTagBug___';
}
}
}
}

if (window.addEventListener)
window.addEventListener("load", function() {fixIeButtonTagBug();}, false)
else if (window.attachEvent)
window.attachEvent("onload", function() {fixIeButtonTagBug();})
</script>

Abraham J.

This is ever SHIT , but I have nestled a form in a form ... not clean job but it works, and have two working submit buttons.
Works in Windows browser and Firefox

Dan H.

Hello Abraham, you're solution works except in Internet Explorer 5.2 for the Mac.

The site I'm working on only has about 0.11% of sessions using Mac IE. So may not be a big deal. Depends on your site.

Chad Lester

Were you doing something like this?

<form>
<input type="text" name="t" value="test">
<form><button type="submit" name="b" value="1">Button 1</button></form>
<form><button type="submit" name="b" value="2">Button 2</button></form>
</form>

I found that nesting forms inside forms does not solve the problem. In IE6 if the user clicks on the second button, the values from the input element are not sent.

minghong

Hi guys, I found that by re-assigning outerHTML of the button element, the value can be fixed automagically.

e.g. forms["form"].onsubmit = function( e )
{
var button = document.activeElement || e.explicitOriginalTarget; // Get the button being pressed (work for IE, Mozilla and Opera only)
alert( button.value ); // The value is wrong
if ( window.ActiveX )
{
button.outerHTML = button.outerHTML;
}
alert( button.value ); // The value is correct
return false; // Just for testing
}

minghong

Typo. Please change "ActiveX" to "ActiveXObject". ;-)

Robert Colburn

I use <button>s for management interfaces. So, the typical case is that I'm displaying several records in a table, and I need the button to identify which record to work on. This was requires no JavaScript, and works on all tested browsers.

This is in php, but it's pretty easy to port to something else.

// Example Form Code Before
foreach($records as $rec)
//Display Fields
echo '<button type="submit" name="save" value="'.$rec['id'].'">S</button>';
echo '<button type="submit" name="del" value="'.$rec['id'].'">X</button>';

// Example Form Code After
foreach($records as $rec){
//Display Fields
echo '<button type="submit" name="save'.$rec['id'].'">S</button>';
echo '<button type="submit" name="del'.$rec['id'].'">X</button>';

//---------------

// Example Processing Code Before
if(isset($_REQUEST['del']){
$rec = $_REQUEST['del'];
//remove code
}

// Example Processing Code After
if(isset($_REQUEST['del']){
foreach($_REQUEST['del'] as $rec){
//remove code
}
}

Robert Colburn

oops
// Example Form Code After
foreach($records as $rec){
//Display Fields
echo '<button type="submit" name="save['.$rec['id'].']">S</button>';
echo '<button type="submit" name="del['.$rec['id'].']">X</button>';

Travis Miller

According to the spec, you're correct - you can have more than one submit button in a form:

http://www.w3.org/TR/html4/interact/forms.html#submit-button

...and it shouldn't matter whether you use the <input> tag or the <button> tag.

Also infuriating: when clicking on <button type="submit" value="theValue">ButtonText</button> in IE6, it submits "ButtonText" as the value of the button, rather than "theValue". Ghod, IE sucks.

Gpali

Another way in PHP

while (list($key, $value) = each(${"HTTP_".$REQUEST_METHOD."_VARS"})){

// Microsoft Internet Explorer don't likes <button></button> http://www.w3.org/TR/html4/interact/forms.html#buttons
// use for name="key" value="value" -> name="#key|value"

if(substr($key,0,1) == "#"){
$aKeyValue = iErepair(substr($key,1));
$key = $aKeyValue[0];
$value = $aKeyValue[1];
$$key = $value;

}
}

// -- IE Button Repair
function iErepair($varName){
$array = explode("|",$varName);
$key = $array[0];
$value = $array[1];
return $array;
}

Castwide

I've been experimenting with JavaScript solutions to the button problem, but this one trumps them all. Thanks.

Simon Bettison

This is by far the most elegent solution imo. It doeasnt rely on client-side functionality, is invisible to the user and still provides valid xhtml to boot.

If i could be so bold as to provide a slightly leaner alternative:

foreach ($_POST as $key => $val)
if(substr($key,0,1) == "#"){
$bits = explode("|",(substr($key,1)));
unset($_POST[$key]);
$_POST[$bits[0]] = $bits[1];
}

Us oldies hate typing ;)

Chad Lester

I found that this does not solve the problem stated on this blog. IE6 will still submit multiple name/value pairs even if the name is of the form #name|value.

Anonymous

The <button>Hello</button> option makes little sense versus <input type="submit" value="Hello"...>.

In my app what if the 'Value' supports several languages?

<button>Hola</button>
<button>Guten Tag</button>

Should I muddy up my submit logic in my controllers for the sake of internationalization?

Norwegian and mad

Well, I am totally on track with the plogger. IE (whatever version) sucks from here to high heaven. First i noticed the f... getElementById bug that those .... ..... at MS hasn't done anything with since 2003.

And today I experienced the way IE uses the <button>-tag. I used a <a href> tag to link the button, which works - as I guess was the idea - in FF and Opera... IE however....

Adam

Hmm, what's with all the Javascript needed to solve this problem?
======================================
If you are using PHP/ASP etc.. why not just do this...

Firstly, I assume the problem is caused because the Value you want to POST isn't the same Value that appears in the button....

Just use some CSS and a clever bit of parsing when you check $_POST["action"]

HTML CODE:
-------------------------
(Basically we put the real value we want to pass inside brackets within the SPAN)

<button name="action" value="Cancel"><span class='button_ie_fix'>(Cancel)</span>Cancel Operation</button>

CSS:
------------------------
(Now we hide that DIV so nobody can see it)

button span.button_ie_fix{
display:none;
}

PHP/ASP/PERL (Whatever)
-----------------------
Just check $_POST["action"] for <SPAN class='button_ie_fix'>(Cancel)</SPAN> and parse out the (value) in the middle...

Something like...

eregi("<SPAN class='button_hiddenvalue'>\(([^\)]*)\)</SPAN>",$_POST["action"],$n);

if($n[1]){
$_POST["action"] = $n[1];
}

====================================
At least that way you have something that works without Javascript.. because if Javascript is turned off, you're form won't work....

You might want to set the button up differently so that text only browsers will still make sense of it...

<button name="toolid" value="34442">Big Tool <span class='button_ie_fix'>[34442]</span></button>

With that you just parse out the value inside [ ] plus it looks neat.

Nyahkitty

This discussion is for buttons,
but I found that using image files
painted to look like buttons and with
links attached to them solved the problem.

Multiple "buttons" in a single form. :-)

Nyahkitty

Also, you could use a GIF
with rollover triggers
if you wanted it to animate
like a button.

fishfinger

Image solutions suck massively:
- won't scale with the user's font size
- completely opaque to screen readers
- won't be cross-platform UI
- will need a new image for every language and every state (rollover, click, enabled, disabled, focus, default etc)

monsterchops

Along those lines I can think of a rather interesting thing that I discover about IE. IE will only accept 30 <style> tags ... after that, it simply ignores them. Ok, yes, there are few times when that many are needed or should be needed but it did a number on my brain for a while.

I don't think that having IE submit a name/value pair for each button is much of an issue ... odd, but not a major upset unless you are reading button values on the server-side to activate a process or whatever (I just tend to ignore them). It used to be that if you did not use a value attribute in an IE button that the pair was not sent ... you could try that ... but then there is the catch 22 ... you'd have to dynamically write to the button value onclick etc. for the button that was pressed.

biznuge

Using the hidden form solution with discrete forms for each and every button instance seems to work, but this means using three times the amount of markup. Have stuck with this solution for now as my app is primarily for IE on a corporate net, but it doesn't stop me wanting to jab microsoft in the neck with a sharp object....

Rth

Easy but very ugly solution. using the Onclick event to change the value of the button to wich ever value you want to pass.

<input type="submit" value="Change" name="change" OnClick="this.value='<value you want to post>'">

Sitehatchery

I've come up with a solution that works in PHP without Javascript in all browsers. I'm sure it would be very easy to do this in other server-side languages as well.

edit value is: '.$id[0].'</p>';
}

if(count($_POST['delete'])){
$id=array_flip($_POST['delete']);
sort($id);
echo '<p>delete value is: '.$id[0].'</p>';
}
 ?>

<form action='test.php' method='post'>
<button type='submit' name='edit[35]' value='35'><img src='edit.gif' /></button>
 <button type='submit' name='delete[35]' value='35'><img src='x.gif' /></button>
</form>

For an explanation, see http://www.sitehatchery.com/blog/index.php/html-button-tag-and-ie-compatibility

kfs

this is perfect.

KDB

What about doing something like this: set both the value attribute and the innerHTML to the actual value you want to submit.

<button type="submit" name="command" value="comand123">command123</button>

However, make that innerHTML invisible by setting the color equal to the background-color.

style="color: white; background-color: white"

Then use absolute positioning to place some text of the actual button label you want to use right over the button. I know that can be done but I'm not that good with CSS positioning. Perhaps someone can produce a working example.

Anyway, still messy but requires no javascript or any special server side code.

KDB

To answer my own question, the problem with putting text over the button is that the button won't click when the cursor is over the text. I can however position a <label> over the button and set the "for" attribute to the button's "id" attribute. That will submit the button value but you don't get any visual feed back when it's clicked so still not a perfect solution.

<html>
<head>
<style type="text/css">
div.btn { position: relative }
input.btn, button { width: 100px; color: #ddeeff; background: #ddeeff }
label.btn { position: absolute; top: 2px; left: 0px; width: 100px; text-align: center }
</style>
</head>
<body>
<h3>Title</h3>
<p>This is some text</p>
<form action="" method="get">
<div class="btn"><input id="123" class="btn" type="submit" name="command" value="123"/><label for="123" class="btn">Howdy</label></div>
<br>
<div class="btn"><button id="123" type="submit" name="command" value="123">123</button><label for="123" class="btn">Howdy</label></div>
</form>
</body>
</html>

dandan

Here is the solution:

do this:

<input type="hidden" name="electionID" VALUE="${electionID}"/>
<button type="submit">Count my votes </button>

So, it will give your input (the hidden stuff) and label the button correctly.

Eric

dandon, that is not a solution. The issue is determining which button was clicked on a form with multiple buttons.

Denes Szabo

onClick="this.value='myrealvalue';" solves the problem. But, the button changes according to 'myrealvalue' but works.

kolibrizas

<input type="hidden" name="actiontype" value="none" id="ietype">
<button type="submit" onclick="document.getElementById('ietype').value='preview';" name="preview">Preview</button>
<button type="submit" onclick="document.getElementById('ietype').value='publish';" name="publish">Publish</button>

this solves the problem as you create a hidden value which changes value depending on the button you clicked. Hope I helped!

Gdbeck

kolibrizas,
Works Great. I always adhere to the KISS philosophy and this is such a simple but effective method. Appreciate the post.

kolibrizas

You are welcome :)
Glad to have helped ;)

Karl Dickman

I have a form that looks something like:
<form method='post' action='Login.php'>
...
<input type='submit' name='action' value='Log in' />
<input type='submit' name='action' value='Reset password' />
</form>

IE7 won't even send the values for the action variable. What's up with that?

Peter

Remember all those websites that used to tell you that the site has been 'optimized for IE'? Well, f**k IE, I'm putting up a msg that says the site has been 'optimized for FireFox, Safari & Opera'! ;-)

Rajee Jha

Please see this link. I think setting the value attribute explicitly on onClick is the cleanest solution. http://lists.evolt.org/archive/Week-of-Mon-20001002/017911.html

rouven

@Rajee: No, this is working for IE7 but not for IE.

rouven

Args... IE6 is not working i meant ;-)

Tommy

What i did was:
<input type="submit" value="Save" name="submit" class="button" onclick="javascript:document.myform.submit();"/>
Works for me in IE7. dunno about the rest.

Davey

Tommy, your solution works great. Thanks.

Thanks PeterB for this blog post also. I was stumped.

jack

Thanks, you saved my butt... I didn't know what was going on. Works great now!

viktor

this bastard (IE) pissed off me too.... HTML_TAG a href="link_here"HTML_TAGinput type="button" name="delete_resp" value="Delete" HTML_TAG/a
doesn't work in IE.... you can click the button 1000 times, nothing will happen! Advice?

Jim

Rth, your solution seems like the easiest, quickest, dirtiest (appropriate for IE) to me.

I tried it in IE6 and Firefox, with multiple buttons in the form. It works fine. I just check (in PHP) that $_POST['btnName'] = 'btnValueSetByJavascriptOnClick';

A pretty quick and relatively easy re-write.

Cheers! Thanks for the solution, Rth and all. Curse MS.

spot

you guys can also try this approach :)http://thespotontheweb.blogspot.com/2009/04/trouble-using-element-in-ie7.html :

Trouble using <button> element in IE (internet Explorer)
I've been having trouble using the <button> in IE7. The problem is IE always uses the "TEXT" between the <button name="action" value="thevalue" >TEXT</button> as the return value from a form POST, instead of "thevalue".

As I observed this only happens in IE6/7 but not on Firefox and Chrome. I've tried to Google for a work around but I usually get solutions using JavaScript... which I also prefer not to use.

Instead, I used the following to get around the issue:

<button name="action[thevalue]" >TEXT</button>

when submitted the result array will be like this:

Array ( [action] => Array ( [thevalue] => TEXT ))

having the array structure above, all I need to do is to get the "thevalue" key of the variable array "action". Here's how I did it in PHP:

<?php
$parameters = $_REQUEST;
$action = implode(array_keys($parameters['action']));
echo "Value of action: ".$action;
?>

the result will be:
Value of action: thevalue

--

That's all to it... well I hope I have given you another option on how to go around the subject.
Feel free to use the code above, and if you find it useful, I would greatly appriace if you atleast provide a feedback via comment.

Lady Watson

This posting is coming up on a 4 year anniversary. Thank you for keeping all the comments active. I used Marc Pujol's solution with html, javascript, and coldfusion session variables (text only for now). I'm new at this but truly see why we all are disgusted with IE's quirks.
now on to my wmplayer issues again IE related.
To see my buttons in action go to
smokeymountaincabinets.com/cabinetry.html

beejamin

Hey kids, here's a neat solution, which you can use nearly everywhere. This is a JS/jQuery version, but it wouldn't be hard to port it to a plain JS or any other library:

if ($.browser.msie) {
var buttons = $('form button[name]');

buttons.each(function(){
$(this)
.after('<input type="hidden" id="buttonSurrogateFor_' + $(this).attr('name') + '" name="' + $(this).attr('name') + '" value="' + this.outerHTML.match(/value="([^"]*)"/i)[1] + '" disabled="disabled"/>')
.click(function() {

$('#buttonSurrogateFor_' + $(this).attr('name')).removeAttr('disabled');//Enable the surrogate that corresponds to this button

$(this).closest('form').find('button').removeAttr('name');//Prevent all buttons submitting values.

});
})
}

The script should be run onDOMReady, and finds all buttons with a name attribute within a form. It creates a surrogate hidden input for each, and extracts the actual value from the IE only OuterHTML property (not the value reported by IE - this returns the innerHtml of the button).

When the button is clicked, the surrogate is enabled (simulating sending only the value of the clicked button), and all the buttons in the form have their names removed, so they aren't submitted at all.

From my quick testing, this produces exactly the same GET/POST content you'd expect from a browser that gets it right.

It does assume that your form is going to request a new page from the server - where removing the button names doesn't cause a problem. If you're using AJAX, you could rename the name attributes to 'nameTemp', and change them back when you're done.

Jacob

There's a much easier solution to this entire issue. Simply give both buttons the same name, and then IE will submit only the value of the one that was clicked. If you need the buttons to have different identifiers, so you can tell them apart, give them different IDs. For example...

<form action="showRequestVariables">
<button type="submit" name="submit-button" id="button1">Button1</button>
<button type="submit" name="submit-button" id="button2">Button2</button>
</form>

Both IE and Firefox will then submit the following...

submit-button = (whichever button was pressed)

That should solve your problem. Hope that helps!

Kenny

Works with IE8 but not IE7...?

Kenny

Actually this will work with IE7 but only if the value parameter is the same as the text within the <button> tag (see post by snobo - 16th October 2009).

<button type="submit" name="submit-button" id="button1" value="Button1">Button1</button>
<button type="submit" name="submit-button" id="button2" value="Button2">Button2</button>

Chileno

an easy solution with "Value"

<button name="asd" value="12" onclick="alert(this.value)">one two</button>

on ie show one two
on firefox show 12

but

<button name="asd" value="12" onclick="this.value='12',alert(this.value)">one two</button>

on ie show 12
on firefox show 12

greetings from chile

Steingo

Thanks for posting this - very nice simple solution.

IE Distressed

I have to say, I have a little bit of a man crush on you right now. That's an awesome, simple solution Chileno.

Simo

don't work in ie6 ! f**k ie6 -_-''

cloudranger

I found a few of the examples given here didn't work well for me - some didn't work at all (were off topic) or others either flashed the value in the button before posting the page, or IE returned more in the post variables than Firefox did. A couple of others whilst working still brought back both buttons so you had no idea which had been pushed.

I came up with my own variation based the version by kolibrizas in this article. My focus was to bring back exactly the same post variables on IE and Firefox (no extra rubbish) and support passing back values (other than the button name or text) in the button - ie bringing back a record key with the delete button.

<?php
print_r($_POST);
?>

<form action='test.php' method='post'>
<input type="hidden" name="" value="" id="ie-save">
<input type="hidden" name="" value="" id="ie-delete">
<button type="submit" onclick="document.getElementById('ie-save').value='save';document.getElementById('ie-save').name='save'" name="" id="save">SAVE</button>
<button type="submit" onclick="document.getElementById('ie-delete').value='1234';document.getElementById('ie-delete').name='delete';" name="" id="delete">DELETE</button>
</form>

The way I avoid bringing back any rubbish in the post variables is to not assign any names to any of the buttons until they are clicked.

As onClick relies on Javascript, in real life, this code snippet it wrapped in a PHP class that I call to generate a button. I identify the browser type and output a standard button string if it is not IE, and the above if it is. That way on a non IE browser there is no workaround code generated (ie the onClicks or hidden fields)

Staszek

I have installed ie8 yesterday and checked ie8 against this bug. It is sad. Bug still exists in new version of IE. I wonder what was guys from Microsoft doing for the last few years.

Aiyoku

Hi, i do not want to use JavaScript so i prefer this solution:
every button must have its own form.

<form method="post" action="index.php">'
<input type="hidden" name="VariableToBePosted" value="yourValue_1">
<input type="submit" value="button_LABEL" />
</form>

<form method="post" action="index.php">'
<input type="hidden" name="VariableToBePosted" value="yourValue_2">
<input type="submit" value="button_LABEL" />
</form>

Now the bad thing is (or maybe not bad) if i have to link more radios, checkBoxes, inputs to specific button, i have to use them in the buttons form and it limits a design.

Aiyoku

sorry, inputs as buttons =]

snobo

@Staszek:
http://msdn.microsoft.com/en-us/library/ms535211(VS.85).aspx says:

"Internet Explorer 8 and later. When the BUTTON element is submitted in a form, the value depends on the current document compatibility mode. In IE8 mode, the value attribute is submitted. In other document modes and earlier versions of Internet Explorer, the innerText value is submitted."

GreatBigMassive

.
.
THE GENERIC SOLUTION
==========================
Here's your solution. You don't have to worry about Javascript or anything like that.

STEP 1: Create your button
--------------------------------------------------------------------------------
<button name='nav' value='next'>Next Page</button>

STEP 2: Create a hidden field for the button
The hidden field should have the same value as the button but its name should be prefixed with 'iefix_'
-------------------------------------------------------------------------------------------------------------------------------
<input type='hidden' name='iefix_nav' value='next' />

STEP 3: Fixing your $_POST Data
--------------------------------------------------------------------------------
This is a PHP code example. Basically, when you submit the form, at the very top of your page before you do anything with your form data, you run this function.

/* Start of function */
function fixPOST(){
foreach($_POST as $k=>$v){
if(substr($k,0,6) == "iefix_"){
$k2 = str_replace("iefix_","",$k);
if(isset($_POST[$k2])){
$_POST[$k2] = $v;
}unset($_POST[$k]);}}}
/* End of function */

STEP 4: Check your POST data
-------------------------------------------------------------------------------
After the function runs, print your post data and you should have everything in place just as you wanted it.

GreatBigMassive

There should be a piece of code around that foreach statement in the fixPOST() function. This would be

if(count($_POST)){

}

Obviously, you do this to make sure the function only runs when $_POST data is detected. DOH!!!!

Jacob

Thank you all so much for this information. I had been stumped for months on this very same problem. It's unbelievable that for nearly 5 years now this has been a problem and MS has done nothing to fix it.

Dave

I got it!

<form name="dForm" id="dForm" action="default.asp" method="post">
<Input type="hidden" name="SubmitIt" value="Yes">
<Input type="hidden" name="ieCrap" value="">

<button type="submit" name="name" id="name" value="YourName" onclick="ieFix(1)"
<img src="/images/image.gif" />
</button>

</form>

<script LANGUAGE="JavaScript">
function ieFix(fix)
{
document.dForm.ieCrap.value=fix
}
</script>

<%
If Request("SubmitIt") = "Yes" Then

if Request("ieCrap") = 1 then
Response.Redirect("wherever")
end if

end if
%>

It works for me

Adam

Here's my way, problem solved the cleanest possible way (if you don't mind using jQuery).

http://my.opera.com/pp-layouts/blog/2010/09/29/html-button-element-in-ie-all-breeds-solved

Mohammad Elsheimy

Very nice tip, but u know, using the <button> element is disregarded and it's better to use <input> for the best rendering. This is a great article about the <button> element: http://particletree.com/features/rediscovering-the-button-element/

Anonymous

Fuck IE its the fucked up web browser in the word so much bugs and unsecured web browser every fucken time it got hacked in hacking contest but not chrome even fire fox got hacked but at list it has no bugs like IE. every fucken time i designed a new website i fund a new bug on IE, what the fuck is that i cant get it.

Peter Bengtsson

Are you angry?

Stryks

No ... Don't fund more bugs. It has enough.

Anonymous

I've been working on web stuff for eight years now and I've only just run into this one. Is that embarrassing? Anyway, it's just an unbelievable screwup on IEs part. I've had people gathered around my machine going "no way - seriously?". It's going to be an absolute nightmare to code around, too.

I hate internet explorer

I.E. is the bane of my existence. I can't put HTML in an INPUT tag, you idiots! I need a form submission button on a graphical background with dynamic text inside... needs to be a button element. But I can't because of I.E.. I.E. is why the web is still in the stone age. FFFFFFFF Internet Explorer!!!!!!!!!!!!!

Kamran Ayub

So, I'm just doing this (an enhancement to Chileno's solution):

//
// IE 7 and below <button> fix
// See: http://www.peterbe.com/plog/button-tag-in-IE
//
if ($.browser.msie) {
if ($.browser.version === "7.0" ||
$.browser.version === "6.0") {
$("button").live('click', function () {
var $this = $(this),
name = $this.attr("name"),
value = $this.attr("value");

// Assemble replacement hidden field, same name, same value
$("<input type='hidden' />")
.attr("name", name)
.val(value)
.insertAfter($this);

// Rename this field so IE doesn't overwrite value
$this.attr("name", "ie_" + name);

// TODO: Do we need to rename any other buttons with the name name?
// As far as I know, it doesn't seem necessary
});
}
}

On page load.

Prevents flashing the value of the button as the text of the button and seems to work great. I added a TODO in case someone runs into the issue, but I tested this with multiple "action" buttons and it works fine.

I use .live() in case of AJAX requests bringing back new buttons.

Zubair.INFO

Not sure if this has been mentioned before, but why not just avoid relying on the value of the button? you can simply pass in a input type=hidden field with the value you need to determine if the selected form or button was click?

bess

or with jquery it's pretty simple to just disable the other button as follows:

$('#fieldset-id button').bind('click', function () {
var myButt = $('#fieldset-id button').not(this)[0];
$(myButt).attr('disabled', 'disabled');
}
});

Courtenay Probert

Hack on the JQuery fix (disables all other bottons):

if ($.browser.msie) {
if (parseInt($.browser.version) < 8) {
$('button').bind('click', function() {
$('button').not(this).each(function() {
$(this).attr('disabled', 'disabled');
});
});
}
}

Courtenay Probert

This version is form specific (doesn't disableother form buttons)

if ($.browser.msie) {
if (parseInt($.browser.version) <= 8) {
$('button[type=submit]').bind('click', function() {
$(this)
.parentsUntil("form")
.find('button[type=submit]').not(this).each(function() {
$(this).attr('disabled', 'disabled');
});
});
}
}

wgarn

In my "particular" case it helped to add:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

That means: page_one.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><body>
<form action="page_two.html">
<button name="info1" type="submit" value="one">Select</button></td>
<button name="info1" type="submit" value="two">Select</button></td>
<button name="info1" type="submit" value="three">Select</button></td>
<input type="hidden" name="info2" value="more-info" />
<input type="hidden" name="info3" value="even-more-info" />
</form>
</body></html>

Andrei Prodan

First of all there is no way more semantic than other. It's either the standard or not. Second, every form element requires a submit input and not necessarily a button. You can have 0 or more buttons in a form that do whatever you want them to do (except submit the form), and 1 or more input type submit elements that actually submit the data to the form action. Stop whining and get it right.

Waseem Khan Web Designer

Hi dear sir how are you? i hop you also fine please help me this issue.

i have use this type "Button" in html but i have create .net theme my problem this i have use aspx button but this button show in browser input type submit.
how can show my button aspx how in html button not show input type submit i have show only button type this is my problem so please help me thanks.

this html button:
<button id="btnSubmit" runat="server" class="button btn-cart" onclick="http://google.com"><span><span>helloo</span></span></button>

this aspx button:
<asp:Button id="button" runat="server" type="button" title="Add to Cart" class="button btn-cart" Text="Add To Cart" />

Anonymous

Microsoft has stopped security updates for IE. Web devs can finally drop support for IE.

Your email will never ever be published.

Related posts

Go to top of the page