最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript: How to detect if an HTML checkbox was selected? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Nov 3, 2009 at 16:56 HankHHankH 12k4 gold badges19 silver badges4 bronze badges
Add a ment  | 

9 Answers 9

Reset to default 12

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:

  • "input:checkbox" finds all the input checkboxes on the page
  • "[name=bedrooms]" finds all the elements with attribute name="bedrooms"
  • ":checked" finds all the elements with attribute checked=true

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.

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>
  <form name="myForm">
    <input type="checkbox" name="myCheck" 
       value="My Check Box"> Check Me
  </form>

   <a href="#" onClick="window.alert(document.myForm.myCheck.checked ? 'Yes' : 'No');">Am I Checked?</a>

This is from a textbook called JavaScript in 10 Easy Steps or Less by Arman Danesh - so i'd assume this works. hope it helps

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.

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

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);
    });
});

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)

Markup:

...<input type="checkbox">...
  1. detect if an HTML checkbox has be clicked/selected?

a: using jQuery 1.7+:

$(function(){
    $("input").click(function () {
        console.log($(this)[0].checked);
    });      
});
  1. retrieve which checkbox(es) have been selected?

a: again using jQuery 1.7+:

console.log($('input:checked'));

Hope this helps.

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

document.GetElementById("cbxCheckbox1");
发布评论

评论列表(0)

  1. 暂无评论