Today at work I came across a situation where we needed to set the default value of a <select> box on a form, normally this would be a perfectly simply operation. If it were a straight php form I would have simply echoed an <option selected...></option>. But we are working with Joomla in a fully MVC context so all is not quite so simple. In wades jQuery with a deserved look of achievement on its face…

So once the form had been set up, and the view was grabbing the correct data from the model to populate the select box it was time to fix this little problem. The solution is very elegant and requires only two lines of jQuery:

jQuery("select#selectBox option[selected]").removeAttr"selected");
jQuery("select#selectBox option[value='requiredValue']").attr("selected","selected");

The first line finds the currently selected value in the select box and removes that attribute. The second line takes a parameter of the thing you want selected (requiredValue in this case) and sets its attribute to be selected. And Bob is your grandad’s sons brother.

I must confess that I did not come up with this solution all by myself (altough I did adapt it to my situtation), I found the original article theMightyBlog of Will Strohl. Thanks a lot Will!