Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have written a tiny bit of jQuery which simply selects all the Select form ele

ID: 646597 • Letter: I

Question

I have written a tiny bit of jQuery which simply selects all the Select form elements on the page and sets the selected property to the correct value. Previously I had to write code to generate the Select in php and specify the Selected attribute for the option that was selected or do loads of if statements in my php page or smarty template.

Obviosly the information about what option is selected still needs to be specified somewhere in the page so the jQuery code can select it.

I decided to create a new attribute on the Select item

<Select name="MySelect" SelectedOption="2"> <-- Custom Attr SelectedOption
<option value="1">My Option 1 </option>
<option value="2">My Option 2 </option> <-- this option will be selected when jquery code runs
<option value="3">My Option 3 </option>
<option value="4">My Option 4 </option>
</Select>
Does anyone see a problem with using a custom attribute to do this, is there a more accepted way, or a better jquery way?

Explanation / Answer

If you are absolutely sure you want this, you should call it data-something.

A new feature being introduced in HTML 5 is the addition of custom data attributes. This is a, seemingly, bizarre addition to the specification - but actually provides a number of useful benefits.

Simply, the specification for custom data attributes states that any attribute that starts with "data-" will be treated as a storage area for private data (private in the sense that the end user can't see it - it doesn't affect layout or presentation).

This is because, otherwise, the HTML you produce is invalid by HTML5 and will fail such validation checks.

This has very little to do with jQuery - jQuery is more about DOM manipulation, what you're really asking is a HTML question which can really only be answered by considering the standards (HTML5 or otherwise). That said, for readability, you should have the value inside the HTML. Anywhere else would just be confusing and unmaintainable in the long run.