MIke MIke - 1 month ago 6
CSS Question

disable button when class on li doesnt exist

I want to prevent the button to be click when there are no item selected in the list. Only enable it when at least 1 in the list have

highlight
class.

HTML

<ul class="list">
<li><input type="checkbox" name="cat[]" id="1" value="227">
<label class="label-list" for="1">Select</label></li>
<li><input type="checkbox" name="cat[]" id="2" value="227">
<label class="label-list" for="2">Select</label></li>
<li><input type="checkbox" name="cat[]" id="3" value="227">
<label class="label-list" for="3">Select</label></li>
<li><input type="checkbox" name="cat[]" id="4" value="227">
<label class="label-list" for="4">Select</label></li>
</ul>

<input type="submit" id="search" class="btn-info" value="search" disabled>


SCRIPT:

$(".list .label-list").click(function() {
$(this).toggleClass("highlight");
});


CSS:

.highlight {background:red;}


FIDDLE

Tried to use this script but how do I toggle the attr from disabled to enabled?

if( $('.list .label-list').hasClass('highlight') === true )
{
$('#search').addClass('active');
}

Answer

You should rather test for is :checked like

var $checkb = $(".list").find("input[type='checkbox']"),
    $search = $("#search");

$checkb.on("change", function(){
	$search.prop("disabled", !$checkb.is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list">
  <li>
    <label>
      <input type="checkbox" name="cat[]" value="224">
      Select
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox" name="cat[]" value="225">
      Select
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox" name="cat[]" value="226">
      Select
    </label>
  </li>
  <li>
    <label>
      <input type="checkbox" name="cat[]" value="227">
      Select
    </label>
  </li>
</ul>

<input type="submit" id="search" class="btn-info" value="search" disabled>