Onlinebase

HTML 5 gotcha

Or how a section tag can break your form

OK, this was a gotcha for me - the new HTML 5 elements are very handy and perfect for structuring your code, but be aware how you use them. I found out the hard way that not adhereing to standards can bite you in the bum. Imagine this piece of example code (real code much more complex, but this is the gist of it):

<section>
<form>
<button type="submit">hit me!</button>
<input name="1"/>
</section>
<section>
<input name="2"/>
<input name="3"/>
</form>
</section>

Doesn't look too shabby right, especially taking into account that this is generated code, based on some (flawed it would seem later) logic of mine ;-) So the second section is sometimes generated to show some extra fields and other stuff. Hence I need to dynamically close the previous section. The bottom part closing the form and the section are outside of the extra logic. This is all well, until you submit the form..., then only the first input element of the form is shown as being posted. Weird or what? At least I thought so. I wracked my brain trying to understand why this happened. It all came down to this:

<section>
<form>
<button type="submit">hit me!</button>
<input name="1"/>
</form>
</section>
<section>
<input name="2"/>
<input name="3"/>
</section>

The browsers rendering engine (all browsers that I had available actually) concluded that I had structured my HTML wrong and rewrote the code to the above example. Truth be told - I witnessed this in the Chrome Developer Toolbar and in Firefox' Firebug. So when I hit submit, it would submit all fields in the form. But the form didn't extend further than the first section. The reason being that in HTML 5 spec a form nested inside a section is seen as a child of that section. Hence it must be closed within the containing section, or as a whole be placed outside of the section. Having seen this behaviour and learned something new, I changed the code to this:

<form>
<section>
<button type="submit">hit me!</button>
<input name="1"/>
</section>
<section>
<input name="2"/>
<input name="3"/>
</section>
</form>

And, "lo and behold, all's well that ends well"! Time for a pat on the shoulder, make a mental note to never code like this again and then go for a nice long bikeride in the sun ;-)

Geplaatst op 10 maart 2015 om 00:00 u.

Alles in 'Ontwikkeling'

10 bericht(en)