HTML Label Tag Causes Mysterious Behavior of ASP.NET Button

Recently, because of my ignorance of the HTML label tag, I encountered a very weird problem. I have a page like this:


And the problem is no matter which button I click, the “Save Student Record” button is always fired. Even I set a break point on the button clicked event handler of the button “New Search”, the break point never gets triggered. If I switch the Save Student Record button and the New Search button, then the New Search button will always get fired.

After I looked at the HTML markup and some Internet search, I finally figured out the problem. First, let’s take a look at the HTML code of the page:

   1: <label class="read-only">

   2:     <asp:Button ID="btnSave" runat="server" Text="Save Student Record" Width="150px"

   3:         OnClick="btnSave_Click" />

   4:     <asp:Button ID="btnCancel" runat="server" Text="New Search" OnClick="btnCancel_Click"

   5:         CausesValidation="False" />  

   6: </label>

Instead of putting the two buttons in a <div> tag, I put them in a <label> tag, and it was the culprit of the weird behavior. When my page is rendered in browser, the <label> tag is automatically bound to the first button in the label, and when I click on any button (actually any place in the label text area), the first button is toggled. It is the expected behavior of an HTML <label> tag (see the definition and usage of a <label> tag). The interesting thing is that FireFox automatically puts the two buttons in two <label> tags when rendering the page, so the problem does not happen in FireFox. But both IE 9 and Google Chrome put the two buttons in one <label> tag, and thus shows the weird behavior.

The above problem can be easily fixed by either putting the two buttons in two separate <label> tags, or changing the <label> tag to the <div> tag.

I hope my mistake can help someone.

Leave a Reply

Notify of