Silas
Silas

Reputation: 582

Controlling Checkboxes in HTML

I am attempting to add a No Preference choice to my check box list and what I would like to happen is as follows:

  1. All checkboxes that are selected become unchecked when "No Preference" is selected.

  2. If "No Preference" is selected and another checkbox is selected, then "No Prefernece" becomes unselected.

Here is what I have so far: http://jsfiddle.net/VuS5R/1/

Thank you for your help.

Upvotes: 2

Views: 451

Answers (3)

Kath
Kath

Reputation: 1854

The elegant solution from jQuery. The "No preference" has "Nop" class, others "pref":

$(document).ready(function ()
{
   $(".Nop").click(function()
   {
        if ($(this).is(":checked"))
        {
             $(".pref").attr("checked", false);      
        }
    });
    $(".pref").click(function()
    {
          if ($(this).is(":checked"))
          {
               $(".Nop").attr("checked", false);      
          }
     });
});

Upvotes: 1

Rémi Breton
Rémi Breton

Reputation: 4259

My suggestion would be to put an ID on the ul element. Then you can use getElementByID and getElementsByTagName to identify the checkboxes. Since the "No preferences" checkbox is the first, bind an event on its click to uncheck all the checkboxes if it is checked.

var checkboxes = document.getElementById('list').getElementsByTagName('input');
checkboxes[0].onclick = function(){
    if(checkboxes[0].checked){
        for(var i = 1; i < checkboxes.length; i++){
            checkboxes[i].checked = false;
        }
    }
}

Here is the jsfiddle.

Upvotes: 2

lkaradashkov
lkaradashkov

Reputation: 8889

  1. First, you have to give each checkbox a unique ID (currently they all have an ID=1).
  2. Then, you would change your "No Preference" checkbox declaration to this:

    input type="checkbox" id="0" name="BT" title="No Preference" value="0" checked="checked" onclick="return NoPreference_ClientClick()"

  3. You will add the following JavaScript to your page:

    function NoPreference_ClientClick() { if ($get("0").checked) { $get("1").checked = $get("2").checked = $get("3").checked = $get("4").checked = $get("5").checked = false; } else { $get("1").checked = $get("2").checked = $get("3").checked = $get("4").checked = $get("5").checked = true; } return false; }

...I hope you get the pattern!

Upvotes: 1

Related Questions