0

I'm still getting to grips with javascript, and am having trouble working out the correct syntax to select a DOM element. Would appreciate any points.

The html:

<div class="container"> 
  <label class="check_box_label">
    <input type="checkbox" class="checkbox">
    Checkbox Label
  </label>
  <select class="select">...</select>
</div>

When the checkbox value changes, if it is checked I want to do something with the select field (I'm using coffeescript)

jQuery ->
  $(".checkbox).change ->
    if $(this).is(":checked")
      $this.xxxxx(".select")

I've studied the jquery api, and experimented with various DOM traversing operators, but must be overlooking something simple. What operator should replace xxxx in my example above? From the API description, I thought closest should work, but it doesn't.

Andy Harvey
  • 12,333
  • 17
  • 93
  • 185
  • 1
    add a `"` here : `$(".checkbox")` – Ivan Chernykh Sep 07 '13 at 14:45
  • Also, if your form is more complex than just these fields, considering using an `id` for each form element to identify them and then the selector in jQuery will be `#yourID`, e.g. `$('#thecheckbox').change( ... ) ` – Niklas Lindblad Sep 07 '13 at 14:47
  • 1
    thanks @NiklasLindblad, unfortunately my form is dynamic, and this section of code is repeated a variable number of times. While I could code a unique identifier, I think in this case DOM traversal is a cleaner approach. – Andy Harvey Sep 07 '13 at 16:27

1 Answers1

3

If this group of elements is always encapsulated within that .container div element then this should work:

$(this).closest('div.conainer').find('.select')

This is using closest to traverse up the DOM hierarchy (parent elements) and then find to traverse back down (child elements).

David
  • 208,112
  • 36
  • 198
  • 279