Skip to content
Advertisement

Adding Attributes to Select Options in Joomla

I’m trying to add extra HTML attributes to some select options in a dropdown list in Joomla 2.5, and want to use the built-in HTML helpers rather than write the HTML by myself. The current output is:

JavaScript

but I would like it to be something like:

JavaScript

so that I can access the data-img attribute using Javascript when the selected option changes.

I’m creating the select options like so:

JavaScript

and then passing them to JHTML to create the generic list HTML:

JavaScript

I’ve looked through the documentation and tried passing various different parameter to the functions, but it’s very confusing in terms of all the options (option.attr, attr etc) that the functions use, and Google has turned up nothing either.

Can anyone tell me what extra parameters I need to pass to the functions to get it properly add the extra attributes to the <option> elements?

Thanks in advance!

Advertisement

Answer

I was struggling on this exact scenario today, needing to add some extra data with the select’s options. After a thorough analyze of the joomla/libraries/joomla/html/html/select.php file, I succeeded to do this with a few downside…

First, in my case, the data used for the select is coming from the database, and need some preparation for this scenario :

JavaScript

Once the data is ready, you can pass it to the JHTML function to build the select :

JavaScript

In short, the ‘option.attr’ must be used to insert attributes into the options. Note : The select.genericlist function MUST have only 3 arguments for this to work. From what I understand from the function, attributes only get merged into the options if you pass exactly 3 arguments to the function, otherwise it just ignores it. So if you want, as exemple, to define a preselected option with the additional parameters, you are out of luck. Here is the part regarding this in the function :

JavaScript

To my understanding, this is a bug and/or a bad behavior. I’ll fill in a bugg in the joomla tracker when I get time.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement