views:

1080

answers:

7

How do I:

  1. detect if an HTML checkbox has be clicked/selected?
  2. retrieve which checkbox(es) have been selected?

Example code:

<FORM ACTION="...">
<INPUT TYPE=CHECKBOX VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="4+">4+ bedrooms<P>
</FORM>

Meaning,

  1. if the web user selects "1 bedroom", I want an event to fire to inform me the user selected "1 bedroom".
  2. As you can see, a user can select multiple checkboxes. For example, they might want to see homes that have either "1 bedroom" or "2 bedrooms". So they would selected both checkboxes. How do I retrieve the checkbox values when multiple checkboxes have been selected?

In case it helps, I would be open to using JQuery to simplify this.

A: 

Assign names and/or IDs to your checkbox elements so that you can distinguish them in code. Then, using jQuery, add events with bind if you want to handle the check/uncheck state changes.

Steve Madsen
A: 

Use IDs on your checkbox.

<FORM ACTION="...">
<INPUT TYPE=CHECKBOX id="c1" VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX id="c2" VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c3" VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c4" VALUE="4+">4+ bedrooms<P>
</FORM>



$('c1').checked // returns whether the 1 bedroom checkbox is true or false
yuku
$('c1').checked is a check to see if it has been selected. I need an Event to fire to inform me that the check box has been selected. How do I create the event to fire if the check box has been selected?
HankH
+1  A: 

1) Use the onclick attribute.
2) You could give them each the same name and use $('input[name=yourname]:checked') to get them all.

[Edit] as requested, here's an SSCCE.

<!doctype html>
<html>
    <head>
        <script src="jquery.js"></script>
        <script>
            $(document).ready(init);

            function init() {
                // Add onclick function to every checkbox with name "bedrooms".
                $('input[name=bedrooms]').click(showCheckedValues);
            }

            function showCheckedValues() {
                // Gather all values of checked checkboxes with name "bedrooms".
                var checked = $('input[name=bedrooms]:checked').map(function() {
                    return this.value;
                }).get();
                alert(checked);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="checkbox" name="bedrooms" value="1">1 bedroom<br>
            <input type="checkbox" name="bedrooms" value="2">2 bedroom<br>
            <input type="checkbox" name="bedrooms" value="3">3 bedroom<br>
            <input type="checkbox" name="bedrooms" value="4+">4+ bedroom<br>
        </form>
    </body>
</html>
BalusC
@BalusC, would you mind elaborating some by showing some code. I'm very excited at your response but am a little unclear exactly how it would work.
HankH
No problem, added an SSCCE.
BalusC
Funny, syntax highlighting went mad in the 2nd <script> and I can't figure how that's been caused.
BalusC
what happen if the <input type="checkbox" name...> is generated dynamically. So when document.ready() fire up, it cant register the click event to the checkbox since the checkbox is not there yet. How can we solve this problem?
Harry Pham
@Harry Pham: replace `jQueryElement.click(function ...)` by `jQueryElement.live('click', function ...)`. API doc: http://api.jquery.com/live/
BalusC
you are the best :)
Harry Pham
A: 

You can use the .checked property on a checkbox to retrieve whether a checkbox has been checked. To fire an event when a checkbox is checked, you can use the click event in jquery. Something like the below would work to list all checkboxes on the page that have been checked.

$("input[type='checkbox']").click(function() {
    // if you want information about the specific checkbox that was clicked        
    alert("checkbox name : " + $(this).name + " | checked : " + $(this).checked);

    // if you want to do something with ALL the checkboxes on click. 
    $.each($["input[type='checkbox']", function(i, checkEl) {
       // put any of your code to do something with the checkboxes here.
       alert("checkbox name : " + checkEl.name + " | checked : " + checkEl.checked);
    });
});
Ryan Brunner
A: 

You can use events to see if a checkbox was selected (onChange). You can read more about it at the Essential Javascript tutorial (see the section entitled: Javascript is an Event Driven Language)

JasCav
+7  A: 

jQuery to the rescue! (since you tagged it as such):

$('input:checkbox[name=bedrooms]').click(function() {
  var values = $('input:checkbox[name=bedrooms]:checked').map(function() {
    return this.value
  }).get();

  // do something with values array
})

(make sure to add a name="bedrooms" attribute in the html for your checkboxes; you'll need them when submitting the form anyway, in order to retrieve them on the server).

I've used a few pseudo-selectors:

Combine them as "input:checkbox[name=bedrooms]:checked" and jQuery gives you all the checked checkboxes.

For each one I pluck out their value attribute into an array you can simply iterate over and do what you wish.

Edit

You can optimize this code to save a reference to your checkboxes instead of telling jQuery to go fetch them all everytime there's a click:

var $checkboxes = $('input:checkbox[name=bedrooms]');
$checkboxes.click(function() {
  var values = $checkboxes
    .filter(function() { return this.checked })
    .map(function() { return this.value })
    .get();

  // do something with values array
})

In this sample I've saved the checkboxes into var $checkboxes. On click of any checkbox, instead of going back to the DOM to grab the checked ones, we simply filter $checkboxes down to only the checkboxes that are checked, and for each one pluck out the value attribute into an array. The get() is just an obscure requirement to convert the "jQueryized" array to a regular JavaScript Array.

Crescent Fresh
Pitfall is that it would collect EVERY checkbox in your document. What if he has more checkboxes than only for bedrooms?
BalusC
Oh, the get(0) only returns 1st element of the map .. Not the raw array.
BalusC
@BalusC: "He" has provided an example of a bunch of checkboxes in a form. That's what the answer is tailored to. If "he" had specific css `class`es, `name`s, or a container then it would have been remiss to exclude them.
Crescent Fresh
@BalusC: yep, good catch!
Crescent Fresh
+1 for your map() idea though.
BalusC
@BalusC: on second thought, what good is a checkbox without a `name` attribute? Answer updated.
Crescent Fresh
A: 

If you do not want to use JQuery you could always use

document.GetElementById("cbxCheckbox1");
GaryDevenay