jay
jay

Reputation: 11

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 (e.g. val_2), I want to determine if the corresponding checkbox (somewhere underneath root_node) is checked.

Upvotes: 1

Views: 659

Answers (2)

Hoff
Hoff

Reputation: 39876

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

Upvotes: 2

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263077

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

Upvotes: 1

Related Questions