Synook

An interesting multi-selector in JS

I made this for selecting categories when writing articles in this blog. The same could be achieved using checkboxes or a select with multiple enables, but what’s the fun in that? Also, this fits on one line and can handle lots of options without tabking up too much space.

JavaScript:

function $(eleid) {
    return document.getElementById(eleid);
}
function select(select) {
    if (select.value != "0") { 
        $("names").innerHTML += "<a href=\"javascript:delcat(" + select.value + ")\">" + options[select.value] + "</a>; ";
        $("selected").value += "[" + select.value + "]"; select.value = "0";
    }
}
function delcat(option_id) {
    $("names").innerHTML = $("names").innerHTML.replace("<a href=\"javascript:delcat(" + option_id + ")\">" + options[option_id] + "</a>; ", "");     
    $("selected").value = $("selected").value.replace("[" + option_id + "]", ""); 
}
var options = {1 : "HTML", 2 : "Javascript", 3 : "PHP};

HTML:

<select onchange="addcat(this)">
    <option value="0" selected="selected">Select below</option>
    <option value="1">HTML</option>
    <option value="2">JavaScript</option>
    <option value="3">CSS</option>
</select>
<span id="names" title="click to remove"></span>      
<input type="hidden" name="selected" id="selected" />

PHP (into array)

$selected = mysql_real_escape_string($selected);     
$selected = substr($selected, 1, strlen($$select) - 2);
$selected = explode("][", $selected);

Sort of pointless, but it may be useful to someone…