Search code examples
jquerytraversal

Traversing the dom, finding the closest previous checkbox


I am trying to traverse the dom in the code below and just having a block mentally. I would like to enable the checkbox in the previous .form-input-wrapper.

<div>
  <div class="form-input-wrapper inline-radio-buttons">
    <span class="button-label">Setup - Ready</span>
    <span>
      <input id="status_0" name="status[0]" type="hidden" value="setup_ready">           
      <input checked="checked" disabled="disabled" id="status_0" name="status[0]" type="checkbox" value="setup_ready">
    </span>
  </div>
  <div class="form-input-wrapper inline-radio-buttons">
    <span class="button-label">Setup - Required</span>
    <span>
      <input id="status_1" name="status[1]" type="hidden" value="setup_required">
      <input checked="checked" disabled="disabled" id="status_1" name="status[1]" type="checkbox" value="setup_required">
    </span>
  </div>
</div>

I've tried a number of things. This is what I currently doing:

(NOTE: this is for context) Basically I have a column of checkboxes. If they are checked they are disabled, except for the last one. if you uncheck the last one, I want to enable the checkbox above.

$(@checkboxes).live 'click', ->
  if $(this).is(':checked')
    return
  else
    console.log "$(this).parents() ", $(this).parent().prev().has(':checkbox').first().find(':checkbox')
    console.log $(this)
    $(this).parent().prev().has(':checkbox').first().find(':checkbox').disabled = false
    return

if I log:

$(this).parent().prev().has(':checkbox').first().find(':checkbox')

this log will just print out the element I clicked on.


Solution

  • You need to go up 2 levels, but I consider it better to use .closest() to specify a selector, rather than hard-coding the number of levels in the code.

    For the first, use:

    $(this).closest(".inline-radio-buttons").siblings().first().find(":checkbox").prop("disabled", false);
    

    For the previous, use:

    $(this).closest(".inline-radio-buttons").prev().find(":checkbox").prop("disabled", false);