Thursday, 24 January 2008

Simple selector list using CSS and Javascript


This tutorial explains how to implement a simple selector list using few lines of code with CSS and Javascript. The result is something like this:




Download this tutorial


Step 1: HTML code
Create a new html page and copy and paste the code below:

<div class="selector_int">Chose topic</div>
<ul id="selector">
<li id="sel1"><input type="checkbox" id="inp1" onClick="javascript:selectElement(1)"/>Technology</li>
<li id="sel2"><input type="checkbox" id="inp2" onClick="javascript:selectElement(2)"/>Science</li>
<li id="sel3"><input type="checkbox" id="inp3" onClick="javascript:selectElement(3)"/>Gaming</li>
<li id="sel4"><input type="checkbox" id="inp4" onClick="javascript:selectElement(4)"/>Lifestyle</li>
<li id="sel5"><input type="checkbox" id="inp5" onClick="javascript:selectElement(5)"/>Entertainment</li>
<li id="sel6"><input type="checkbox" id="inp6" onClick="javascript:selectElement(16)"/>Sport</li>
</ul>
<div class="selector_footer">
<input type="button" value="Save">
</div>


When you check an input checkbox, the relative row going to change the background color in a light yellow. To implement this effect I used a simple javascript function (see step 3) which is called using this code:

onClick="javascript:selectElement(id)

...where id is an integer which identifies the current elements.

You can populate dinamically this list using for example query results in PHP. For example, this is a query which return id_desc_pk (primary key) and description from the table TOPIC:

<?php
$getTopic_sql = 'SELECT id_desc_pk, description FROM TOPIC';
$getTopic = mysql_query($getTopic_sql);
?>

...and this is the PHP code to add dinamically <li> element from getTopic query:

<?php while ($row = mysql_fetch_array($getTopic)) {?>
<li id="
sel<?php echo $row['id_desc_pk']; ?>"><input type="checkbox" id="inp<?php echo $row['id_desc_pk']; ?>" onClick="javascript:selectElement(<?php echo $row['id_desc_pk']; ?>)"/>
<?php echo $row['description']; ?></li>
<?php } ?>


Step 3: Javascript function
This simple function chages the color of row background when a checkbox is selected. You can modify the color "on selected" changing colorSelected variable value (now is #FFFFCC).

<script language="javascript">
function selectElement(idElement){
var colorSelected = '#FFFFCC';
var colorNoSelected = '#FFFFFF';
liElement = document.getElementById('sel'+idElement);
inputElement = document.getElementById('inp'+idElement);
if(liElement.style.background==''){
liElement.style.background = colorSelected;
} else {
liElement.style.background = colorNoSelected;
}
}
</script>

Add this function into <head> tag of your page and try the result.

Download this tutorial

No comments:

Post a Comment