Avoid same IDs for HTML elements

Many back-end developers don’t care about clearance of HTML code. They think it is a front-end developers job…

Yes, but no 🙂 Developers should create a bulletproof code on both sides.

Very often, calling the PHP code, that generates some HTML template, for the second time creates two sets of HTML elements with the same IDs. This is wrong!

Here is a workaround to avoid same IDs for HTML elements using a global variable:

<?php
global $some_global_variable;
if (isset($some_global_variable)) $some_global_variable += 1; else $some_global_variable = 0;   

$form_id = '';
if ($some_global_variable > 0) $form_id = $some_global_variable;
?>

This is an example of HTML template for this hack:

<form role="search" method="get" id="searchForm<?php echo $form_id ?>" class="searchForm" action="/search/">
    <input type="text" id="searchText<?php echo $form_id ?>" name="search" value="" />
    <input type="submit" id="searchButton<?php echo $form_id ?>" value="" />
</form>

Try to be a good programmer every-time and everywhere!

Author: BgRnD Official

Official representative of BgRnd Team on this website

Leave a Reply