简体   繁体   中英

jQuery checkbox selector question

Given some markup where there are a series of inputs (checkboxes) at an arbitrary depth, how can I determine if a given input is checked based on its value:

<ul id="root_node">
  ...
  <li>
    ...
    <span>
      <input value="val_1" ... />
      ...
      <input value="val_2" ... />
      ...

So, what I need is: given root_node and an input value (eg val_2 ), I want to determine if the corresponding checkbox (somewhere underneath root_node) is checked.

You can jQuery selections based on attributes: http://api.jquery.com/attribute-equals-selector and the :checked 'pseudo class'

$('input[value="val_1"]:checked')

so you could do:

if $('input[value="val_1"]:checked').val() !== undefined) {
  // do something
}

Hope this help,

Martin

You can do something like:

var context = "root_node";
var value = "val_2";

var checked = $("input:checkbox[value='" + value + "']",
    $("#" + context)).attr("checked");

If the context never changes, you can shorten the above into:

var checked = $("#root_node input:checkbox[value='" + value + "']")
    .attr("checked");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM