Why Use Bracket Notation in HTML5? - html

This is a "best practices" question. I was perusing the Code Review StackExchage site, and I saw this thread. In it, Joseph Silber makes the suggestion of using bracket notation and eschewing IDs entirely for a form with multiple identically-structured rows of form inputs.
In the books I've read on web design/development, I've never seen this strategy used. Is using bracket notation and wrapping input elements within label tags, as well as not using id tags in form inputs a good idea? Perhaps there something about Javascript/JQuery that makes this approach advantageous?
I wanted to ask Joseph about it directly, but I don't have any reputation on the site yet so I couldn't even comment. However, I'm interested in seeing the community-wide perspective on this, because searching for things like "HTML5 bracket notation" and "HTML5 arraylike notation" isn't turning up anything definitive for me so far.
Here's a summary of the above question with some example code borrowed from the linked question:
Why use this:
<label>Comment:
<input type="text" name="comment[]" width="50" />
</label>
instead of this:
<label for="comment-0">Comment: </label>
<input type="text" id="comment-0" name="comment-0" width="50" />
in a form with multiple rows of the same inputs?

Sticking [] on the end of an input name will cause some server side form processing libraries to present the data as an array. Some other form processors don't need the special syntax. Your choice will largely depend on your desire to be compatible with the former kind vs having more complicated names and not being able to access the elements via dot-notation in JS.
Using child elements instead of for attributes will:
Save you from having to generate unique ids (especially useful if similar forms can appear on a single page)
Limit your styling choices
Be compatible with fewer browsers (I think the only loss is old versions of IE, which is no big loss).
So there are pros and cons there and you have to decide what it right for you.

Related

Naming convention for web projects

It is typical in web projects to have multiple solutions work together to produce the desired outcome. In my case, I am currently working on a project that uses the following: HTML, CSS, JavaScript, jQuery, AJAX, JSON, PHP, MySQL, and some other libraries. This is a typical set of technologies for the average project.
At one point throughout the project, and as you might expect, you would need to interact with data that goes across from HTML to PHP via an AJAX call as a JSON object after being processed by either JavaScript or jQuery, and of course this input data is styled via CSS when displayed to the user.
An example of such HTML element is the following:
<input type="text" name="my-input-name" id="my-input-name" />
Note that the name and id are hyphenated. This could also be written as
<input type="text" name="my_input_name" id="my_input_name" />
Or
<input type="text" name="myInputName" id="myInputName" />
That name and id is what could be used by all the aforementioned technologies.
Personally, I prefer hyphenated for CSS, underscore for PHP, camel case for AJAX, and so on.
But then this means the name and id will not follow the desired naming convention in at least one of the used technologies.
I read many many different opinions (including some in Stack Overflow), but none really provided any final conclusion.
So, my question is, which convention should I use? What is best in HTML 5 and CSS 3 era?
Thanks
It really depends on the style/standards of the project you are using. I've seen all three styles you mentioned. If I may make a recommendation though, I've seen dashes "-" break certain scripts in a Linux environment. Also, underscores "_" are sometimes considered extra clutter if not needed.
If no other style concerns are important, I would recommend the third option of camel case (myInputName). The reason would be in a web environment, things have to be re-compiled each time, so fewer characters are slightly less processing.

input type="number" with currency formatting (thousands delimiters)

This has already been asked numerously and lots of examples have been provided, either with tons of JavaScript, or using the inputmode or the pattern attribute with some regex. However, none of these seem to work together with the numeric keyboard (at least not on my iPhone).
Therefore my question: is this impossible? (in plain and simple HTML5)
I need an <input> for currency with on-the-fly formatting, to edit numbers like this: 1,000,000.00 or, when changing the country, to 1 234 567,89 AND the numeric keyboard appears (important for mobiles). Notice the thousands separators.
Only HTML5 will not work today. (6-6-2016)
What you want is this:
<input type="text" pattern="your-pattern" inputmode="numeric">
However, inputmode is not supported in any browser yet.
The code above explained:
We can't use type="number" because the pattern attribute is not supported on that type, so we use type="text". A better choice might be type="tel" because it's also concerned with numbers and delimiters. However, I don't know the semantic implications of this (on SEO and screenreaders for instances). The safest approach is text
inputmode is new and allows you to specify what kind of input mode is required. Especially useful for mobile devices, as you can imagine
Considering you want to have on the fly conversion from one standard notation to another, you will have to use JavaScript so you can use it for your pattern validation if you really want to use a number type. Or maybe there is even another public API to control the keyboard through JS (but I doubt it, may cause security issues).
Finally, as always: if your validation is important, do it server-side. The client-side should never be trusted. (Even if they have cookies.)

Showing html site Access Keys

I am trying to come up with a good way of displaying Access Key shortcuts on my html5 page.
Some places recommend using the first letter of a link/tab/heading/whatever as the access key, so as to be intuitive. Those places generally recommend that you "subtly" hint to the user that it is an access key by styling it differently to the rest of the heading--that is, to make it underlined, or italic, or bold. This sounds like it would be very ugly, and make people think that it is a bug!
Other places recommend using numbers as access keys, so as not to conflict with browser or device built-in access keys. Those places generally recommend showing access keys after the heading in brackets. This sounds even uglier, and less clear!
Is there a better way of choosing access keys, and how to display them?
Edit:
I really liked #Luke2012's recommendation of using both a letter and a number like:
<input type="search" name="q" accesskey="s 0">
BUT while this works beautifully in IE, it disables ALL of the access keys for the element in firefox or chrome.
You can use both letters and numbers as access keys which make it easier over a range of devices. For example:
<form action="/search">
<label>Search: <input type="search" name="q" accesskey="s 0"></label>
<input type="submit">
</form>
Both s and 0 will trigger the shortcut key.
As far as displaying the shortcuts to a user, what about an information icon that can be hovered (like a tooltip) to explain the shortcut keys. Or a subtle dotted line under the element that will trigger a tooltip when hovered.
There are two options that came to my mind:
A) Some programs, for example the CMS Plone, provide short, automated overviews with a list of the used shortcuts. You could display a link to your users to some "help" page where those are explained.
B) It is very common that accesskeys are underlined when pressing the Alt key. You could mimic such a behavior using JavaScript. You could even read the given accesskey from the the HTML attribute and enclose the first matching character with a span.accesskey or something alike to automate the task of highlighting the the accesskey characters.
If you choose a letter, it seems to me they can be memorized more easily.
How to show them: Use the kbd element.
Where to show them: This depends on your site. Typically, access keys are useful for regular visitors, not for new users. So it might not be necessary to show the keys on every page, as regular users will likely memorize them anyway. Instead, document this feature on a separate page (or as part of a relevant existing page).
If you should use them at all, and in which way you should communicate existing access keys to your users, is probably best discussed at https://ux.stackexchange.com/.

Is it good practice to give html elements id attributes that are only to be used for testing purposes?

Suppose I have a form like so:
<form action="/foo" method="POST">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="Login">
</form>
In my case, there is no need for me to give any of the input tags an "id" attribute. It isn't styled via CSS, there is no javascript referencing it, etc... However, there is a QA department that would love it if it had a hardcoded "id" such as "login-button" so that their automated test would stay stable.
CONS As the developer a am highly skeptical about adding id attributes that serve no functional purpose.
I think it clutters the code.
Confuses future developers looking at
it.
Binds us to whatever testing tool is being used at the time.
Binds us to code outside of the product's codebase.
Starts down a slippery slope of the code knowing something about how it will be tested and vice-versa.
PROS:
From the QA perspective, I can certainly sympathize that this would:
make their work easier.
provide stability (in the short term)
Can I get some help expanding on the Pros/Cons lists I have started here?
One important functional reason to include id attributes on form inputs is so that you can explicitly associate the corresponding label elements with the inputs:
<form action="/foo" method="POST">
<label for="username">User Name</label>
<input type="text" id="username" name="username">
</form>
This is important for accessibility and usability. Screen reader users rely on this association so that they know what input they are typing into. There's also a huge usability difference when the labels are properly associated (user can click on the label to set the focus to the associated input). This is really apparent with checkbox and radio inputs.
Fiddle with example of both on checkboxes. (Note how much easier it is to click on the label rather than the input itself)
As for your opposition... I'm not sure how adding id attributes does any of the "cons" you state. Clutter? nope, valid usable code. Confusing? nope, id's and properly associated labels would be the first thing I'd add if I saw that code. Binds you to a test tool and outside code? how exactly? The fact that it would make your testing crew's life easier is just icing on the cake.
Your first 2 Cons are valid, but I disagree with the last 3.
You could take the stance that you will provide logical element Id's for your testers, but they are responsible for utilizing them with whatever testing tools etc... that they use. This means that you are test/tool agnostic, you just provide the Id's for testing use without necessarily knowing exactly how they will be used.
Adding Id's like this is fairly standard practice for a lot of web apps today.
If possible, their testing tool should fill in the fields based on their name attributes and the form's action attribute if there are multiple forms on the page. These are guaranteed to be as stable as the part of the server answering the POST request.
Ids, field ordering, and other attributes might change due to front-end reasons.
For me it depends. It depends on if the elements can be easily and reliably found without the ID.
In your example, yes, so adding the ID isn't a waste but just isn't necessary. However that's all that is, an example.
In a lot of web pages, as they become more complex and complicated, ID's become your friend, because without it you will need to look at other ways of finding elements.
Especially in the Selenium world, when you come across this problem, you generally turn to CSS and/or XPath selectors.
Other selectors are not bad things, but they can quite slow in older browsers, if you support them.

So what if custom HTML attributes aren't valid XHTML?

I know that is the reason some people don't approve of them, but does it really matter? I think that the power that they provide, in interacting with JavaScript and storing and sending information from and to the server, outweighs the validation concern. Am I missing something? What are the ramifications of "invalid" HTML? And wouldn't a custom DTD resolve them anyway?
The ramification is that w3c comes along in 2, 5, 10 years and creates an attribute with the same name. Now your page is broken.
HTML5 is going to provide a data attribute type for legal custom attributes (like data-myattr="foo") so maybe you could start using that now and be reasonably safe from future name collisions.
Finally, you may be overlooking that custom logic is the rational behind the class attribute. Although it is generally thought of as a style attribute it is in reality a legal way to set custom meta-properties on an element. Unfortunately you are basically limited to boolean properties which is why HTML5 is adding the data prefix.
BTW, by "basically boolean" I mean in principle. In reality there is nothing to stop you using a seperator in your class name to define custom values as well as attributes.
class="document docId.56 permissions.RW"
Yes you can legally add custom attributes by using "data".
For example:
<div id="testDiv" data-myData="just testing"></div>
After that, just use the latest version of jquery to do something like:
alert($('#testDiv').data('myData'))
or to set a data attribute:
$('#testDiv').data('myData', 'new custom data')
And since jQuery works in almost all browsers, you shouldn't have any problems ;)
update
data-myData may be converted to data-mydata in some browsers, as far as the javascript engine is concerned. Best to keep it lowercase all the way.
Validation is not an end in itself, but a tool to be used to help catch mistakes early, and reduce the number of mysterious rendering and behavioural issues that your web pages may face when used on multiple browser types.
Adding custom attributes will not affect either of these issues now, and unlikely to do so in the future, but because they don't validate, it means that when you come to assess the output of a validation of your page, you will need to carefully pick between the validation issues that matter, and the ones that don't. Each time you change your page and revalidate, you have to repeat this operation. If your page validates entirely then you get a nice green PASS message, and you can move on the next stage of testing, or to the next change that needs to be made.
I've seen people obsessed with validation doing far worse/weird things than using a simple custom attribute:
<base href="http://example.com/" /><!--[if IE]></base><![endif]-->
In my opinion, custom attributes really don't matter. As other say, it may be good to watch out for future additions of attributes in the standards. But now we have data-* attributes in HTML5, so we're saved.
What really matters is that you have properly nested tags, and properly quoted attribute values.
I even use custom tag names (those introduced by HTML5, like header, footer, etc), but these ones have problems in IE.
By the way, I often find ironically how all those validation zealots bow in front of Google's clever tricks, like iframe uploads.
Instead of using custom attributes, you can associate your HTML elements with the attributes using JSON:
var customAttributes = { 'Id1': { 'custAttrib1': '', ... }, ... };
And as for the ramifications, see SpliFF's answer.
Storing multiple values in the class attribute is not correct code encapsulation and just a convoluted hack way of doing things. Take a custom ad rotator for instance that uses jquery. It is much cleaner on the page to do
<div class="left blue imagerotator" AdsImagesDir="images/ads/" startWithImage="0" endWithImage="10" rotatorTimerSeconds="3" />
and let some simple jquery code do the work from here.
Any developer or web designer now can work on the ad rotator and change values to this when asked without much ado.
Coming back to project a year later or coming into a new one where the previous developer split and went to an island somewhere in the pacific can be hell trying to figure out intentions when code is written in an unclear encrypted manner like this:
<div class="left blue imagerotator dir:images-ads endwith:10 t:3 tf:yes" />
When we write code in c# and other languages we don't write code putting all custom properties in one property as a space delimited string and end up having to parse that string every time we need to access or write to it. Think about the next person that will work on your code.
The thing with validation is that TODAY it may not matter, but you cannot know if it's going to matter tomorrow (and, by Murphy's law, it WILL matter tomorrow).
It's just better to choose a future-proof alternative. If they don't exist (they do in this particular case), the way to go is to invent a future proof alternative.
Using custom attributes is probably harmless, but still, why choose a potentially harmful solution just because you think (you can never be sure) it will cause no harm?. It might be worth to discuss this further if the future proof alternative was too costly or unwieldy, but this is certainly not the case.
Old discussion but nevertheless; in my opinion since html is a mark-up and not a progamming language, it should always be interpreted with leniency for mark-up 'errors'. A browser is perfectly able to do so. I don't think this will and should change ever. Therefore, the only important practical criteria is that your html will be displayed correctly by most browsers and will continue to do so in, say a few years. After that time, your html will probalbly be redesigned anyway.
Just to add my ingredient to the mix, validation is also important when you need to create content that can/could be post-processed using automated tools. If your content is valid you can much more easily convert markup from one format to another. For example, doing valid XHTML to XML with a specific schema is Much easier when parsing data that you know and can verify to follow a predictable format.
I, for example NEED my content to be valid XHTML because very often it is converted into XML for various jobs and then converted back without data loss or unexpected rendering results.
Well it depends on your client/boss/etc .. do they require it be validating XHTML?
Some people say there are a lot of workarounds - and depending on the sceneraio, they can work great. This includes adding classes, leveraging the rel attribute, and someone that has even written their own parser to extract JSON from HTML comments.
HTML5 provides a standard way to do this, prefix your custom attributes with "data-". I would recommend doing this now anyway, as there is a chance you may use an attribute that will be used down the track in standard XHTML.
Using non-standard HTML could make the browser render the page in "quirks mode", in which case some other parts of the page may render differently, and other things like positioning may be slightly different. Using a custom DTD may get around this, though.
Because they're not standard you have no idea what might happen, neither now, nor in the future. As others have said W3C might start using those same names in the future. But what's even more dangerous is that you don't know what the developers of "browser xxx" have done when they encounter they.
Maybe the page is rendered in quirks mode, maybe the page doesn't render at all on some obscure mobile browser, maybe the browser will leak memory, maybe a virus killer will choke on your page, etc, etc, etc.
I know that following the standards religiously might seem like snobbery. However once you have experienced problems due to not following them, you tend to stop thinking like that. However, then it's mostly too late, and you need to start your application from scratch with a different framework...
I think developers validate just to validate, but there is something to be said for the fact that it keeps markup clean. However, because every (exaggeration warning!) browser displays everything differently there really is no standard. We try to follow standards because it makes us feel like we at least have some direction. Some people argue that keeping code standard will prevent issues and conflicts in the future. My opinion: Screw that nobody implements standards correctly and fully today anyway, might as well assume all your code will fail eventually. If it works it works, use it, unless its messy or your just trying to ignore standards to stick it to W3C or something. I think its important to remember that standards are implemented very slowly, has the web changed all that much in 5 years. I'm sure anyone will have years of notice when they need to fix a potential conflict. No reason to plan for compatibility of standards in the future when you can't even rely on today's standards.
Oh I almost forgot, if your code doesn't validate 10 baby kittens will die. Are you a kitten killer?
Jquery .html(markup) doesn't work if markup is invalid.
Validation
You shouldn't need custom attributes to provide validation. A better approach would be to add validation based on fields actual task.
Assign meaning by using classes. I have classnames like:
date (Dates)
zip (Zip code)
area (Areas)
ssn (Social security number)
Example markup:
<input class="date" name="date" value="2011-08-09" />
Example javascript (with jQuery):
$('.date').validate(); // use your custom function/framework etc here.
If you need special validators for a certain or scenario you just invent new classes (or use selectors) for your
special case:
Example for checking if two passwords match:
<input id="password" />
<input id="password-confirm" />
if($('#password').val() != $('#password-confirm').val())
{
// do something if the passwords don't match
}
(This approach works quite seamless with both jQuery validation and the mvc .net framework and probably others too)
Bonus: You can assign multiple classes separated with a space class="ssn custom-one custom-two"
Sending information "from and to the server"
If you need to pass data back, use <input type="hidden" />. They work out of the box.
(Make sure you don't pass any sensitive data with hidden inputs since they can be modified by the user with almost no effort at all)