AJAX event handling with prototype
Separating CSS and HTML has been the big fuss for a while now. So why not separate your Javascript and HTML as well? Using event handlers instead of using the old onclick="somefunction()" can make your codebase a lot more manageable and clean. I'll demonstrate this technique by using prototype.js, a very nice and lean AJAX framework.
My goal is to create two lists (ul elements) with several <li>. Each of these li elements have checkboxes. And when you click on these checkboxes they will move from one list to the other. Okay, lets get cracking...
We'll have to have some html markup.
<ul id="companies"><li>
<input name="company" value="1" type="checkbox" />Company 1
</li>
<li>
<input name="company" value="1" type="checkbox" />Company 2
</li>
<li>
<input name="company" value="1" type="checkbox" />Company 3
</li>
</ul>
<ul id="selected">
</ul>
Then we will create our javascript.
// create a init method which will do all our initialization function init() { // use css selectors to fetch all checkboxes with name company. var checked = $$('input[type="checkbox"][name="company"]') for (var i = 0; i < checked.length; ++i) { var elem = checked[i] elem.observe('click', select) // register an event handler that registers an 'click' event on every checkbox } } // The select function that will actually do our work function select(event) { var noexportlist = $('companies') var exportlist = $('selected') var elem = event.element() var li = elem.ancestors()[0] // get the supporting li tag. if (elem.checked == true) { exportlist.insertBefore(li, exportlist.lastChild) } else { noexportlist.insertBefore(li, noexportlist.lastChild) } } // and run the init() method when our html document is ready loaded with all our DOM elements. Event.observe(window, 'load', init, false)
And we're home free. Clicking on any of the checkboxes will now move them to and from the respective lists.
You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.







