Skip to content Skip to sidebar Skip to footer

Disable/enable Checkboxes Based On Its Values And Selected Option

I need to hardcode those of the values of the checkboxes which are enabled/disabled, depending on the selected option value. I was trying to do something like this: But no desired

Solution 1:

You need to filter check-boxes based on values so use $.fn.filter. Currently you are setting its value using $(".dissable").val("3")

Reduce the set of matched elements to those that match the selector or pass the function's test.

Code

$("#Units").on("change", function () {
    //Filter checkboxes whose value is 3 or 4
    $(".dissable").filter(function(){ 
        return $(this).val() == 3 || $(this).val() == 4;
    }).prop("disabled", $(this).val() == "Finance");  //disable or enable based on condition
}).trigger('change');

DEMO

Solution 2:

Use the following selector:

$(".dissable[value='3']").prop("disabled", true);

The [value='3'] creates a selection based on the value. See working example:

$("#Units").on("change", function () {
  if ($(this).val() !== "Finance") {
    $(".dissable[value='3']").prop("disabled", true); 
    $(".dissable[value='4']").prop("disabled", true); 
  } else {
    $(".dissable[value='3']").prop("disabled", false);
    $(".dissable[value='4']").prop("disabled", false);
  }
}).trigger('change');
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><selectid="Units"><optionvalue="Marketing" > Marketing </option><optionvalue="Finance" > Finance </option><optionvalue="Operations" > Operations </option></select><inputtype="checkbox"class="dissable"onclick="check();"value="1" /> chbx1
<inputtype="checkbox"class="dissable"onclick="check();"value="2" /> chbx2
<inputtype="checkbox"class="dissable"onclick="check();"value="3" /> chbx3
<inputtype="checkbox"class="dissable"onclick="check();"value="4" /> chbx4
(fiddle: http://jsfiddle.net/2sw3q8p4/)

Solution 3:

Try caching $(".dissable") , utilizing .slice() on cached selector

functioncheck() {}

var disable = $(".dissable");

$("#Units").on("change", function() {
  if ($(this).val() !== "Finance") {
    // disable `.dissable` at index `2,` `3`
    disable.slice(2, 4).prop("disabled", true);
  } else {
    // enable `.dissable` at index `2,` `3`
    disable.slice(2, 4).prop("disabled", false);
  }
}).trigger("change");
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><selectid="Units"><optionvalue="Marketing">Marketing</option><optionvalue="Finance">Finance</option><optionvalue="Operations">Operations</option></select><inputtype="checkbox"class="dissable"onclick="check();"value="1">chbx1
<inputtype="checkbox"class="dissable"onclick="check();"value="2">chbx2
<inputtype="checkbox"class="dissable"onclick="check();"value="3">chbx3
<inputtype="checkbox"class="dissable"onclick="check();"value="4">chbx4

Post a Comment for "Disable/enable Checkboxes Based On Its Values And Selected Option"