HTML

Toggle radio buttons by clicking the label

I’ve seen a few methods of this using over-elaborate JavaScript, when its really not necessary.

All you need to do is wrap the <input with a <label – as a label will¬†inherently¬†become a ‘clicky’ for its children:

<label><input type="radio" name="radio-option" value="cake" />cake</label>
<label><input type="radio" name="radio-option" value="biscuits" />biscuits</label>

 

Easy

Sorting a SELECT with JQuery

Just a simple function to sort an already populated list. Obviously it would be easier to sort before populating, but there are the odd occasion where this is more complicated than you thought.

Requirements : JQuery

var selectOptions = $("#selectId option");

Then, we just run the sort command on the options array – and this easily sorts the items.

selectOptions.sort(function(a, b) {
    if (a.text > b.text) {
        return 1;
    }
    else if (a.text < b.text) {
        return -1;
    }
    else {
        return 0
    }
});

Then, at the end empty the select object and re-append the sorted options array

$("#selectId").empty().append(selectOptions);

Note. I just found a problem with this. If you have already selected an option, that selection will be lost unless you save the selection value before sorting and replace it at the end:

var selectedOption = $('#selectId').val();

And then to restore it

$('#selectId').val(selectedOption);

TabIndex in HTML

TabIndex is an attribute to HTML elements that tells the browser which control takes focus next when TAB is pressed.

<input id="one" tabindex="3" />

<input id="two" tabindex="1" />

<input id="three" tabindex="2" />

<input id="four" tabindex="4" />

Here, once the page is loaded, the first TAB press will set focus to input two, and then subsequent presses will move the focus to three, one and then four – before returning to two.

In a static web page it can be useful, but in a dynamic page, then this is a truely awful way of moving around.Especially as a web browser will automatically give the controls their own order, naturally in the order that they appear in the HTML source.

So why use it? I have no idea. I have never needed this attribute, and cannot ever see me ever using it.

I’ve just had to remove all the wonky tabindex’s from a huge page. Luckily I use an IDE that lets me search and replace using regular expressions! Online Regular Expression Testing Tool