1

Hi I am using Titanium to create a table of row that can be checked.

I need to write some code in Javascript that allows only one row to be checked and when one is checked the other ones are unchecked.

I am not worried about Titanium part but more about a general solution.

I know I need to setup an array of all the rows. What do I do next when one box is checked? How would I go through the other ones and tell them to become unchecked?

Thanks for your help.

Leonardo Amigoni
  • 2,237
  • 5
  • 25
  • 35

3 Answers3

1

Try something like this:

var checkboxes = document.querySelectorAll('#myTable input[type="checkbox"]'),
    checkboxClickHandler,
    i;
checkboxClickHandler = function (event) {
    var i;

    // only uncheck if target is a checkbox which has been checked
    if (event.target.checked) {
        for (i = 0; i < checkboxes.length; i++) {

            // don't uncheck clicked box
            if (checkboxes[i] !== event.target) {
                checkboxes[i].checked = false;
            }
        }
    }
};
document.getElementById('#myTable').addEventListener('click', checkboxClickHandler, false);
Nathan MacInnes
  • 11,033
  • 4
  • 35
  • 50
1

Live example : http://jsfiddle.net/ztm82/

function doit(table, event) {
    if (event.target.nodeName === "INPUT"
        && event.target.type === "checkbox"
        && event.target.checked)
    {
        var rows = table.tBodies[0].rows;

        for (var i = 0; i < rows.length; i++)
        {
            var input = rows[i].getElementsByTagName("INPUT")[0];

            if (input !== event.target)
            {
                input.checked = false;
            }
        }
    }
}
Francis
  • 3,335
  • 20
  • 46
0

Mutually exclusive checkboxes? Why not use radio buttons (<input type='radio'>) instead? You'd get this behaviour for free and it would be more intuitive for users.

Duncan Smart
  • 31,172
  • 10
  • 68
  • 70