billy
billy

Reputation: 157

jquery value in dropdown selected disable checkbox

I am trying to use jquery to disable a checkbox when the selected value of the dropdown menu is anything other than 0. My problem is when I select the item with the 0 value the checkbox is being disabled and to get the checkbox to disable I have to select at least two or more values before it will disbale the checkbox.

An example of my code is here:

example code at js fiddle

When the selected value is 0 I want the checkbox and drop down to be enabled and when the selected value is anything other than 0 I want to disable the checkbox. I also would like it to work whether I start from the first row, bottom, row, or middle row.

Upvotes: 1

Views: 3840

Answers (3)

Dan Tao
Dan Tao

Reputation: 128317

Try this (it works for me):

$("select").change(function() {
  var $this = $(this),
      $checkbox = $this.parent().prev().find("input");

  if ($this.val() != 0) {
    $checkbox.attr("disabled", true);
  } else {
    $checkbox.removeAttr("disabled");
  }
});

$(":checkbox").change(function() {
  var $this = $(this),
      $select = $this.parent().next().find("select");

  if ($this.is(":checked")) {
    $select.attr("disabled", true);
  } else {
    $select.removeAttr("disabled");
  }
});

Upvotes: 1

karim79
karim79

Reputation: 342625

This should do it, if my understanding of your problem is correct:

$("select").change(function() {
    $(this).closest("td").prev().find(":checkbox").prop("disabled", $(this).val() !== "0");
});

$(":checkbox").change(function() {
   $(this).parent().next().find("select").prop("disabled", this.checked);
});

Your updated fiddle.

Upvotes: 2

PhonicUK
PhonicUK

Reputation: 13844

That's because at the 'change' event, the value you get is before the change is actually finished, so the change that the user is making 'now' doesn't show until the next time the event fires.

You want to use something like onblur, onmouseup or onkeyup to be notified post-change that you want to change the property of the check box.

Upvotes: 0

Related Questions