MIke
MIke

Reputation: 619

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');
}

Upvotes: 2

Views: 404

Answers (2)

Beginner
Beginner

Reputation: 4153

you can simple count all selected checkbox with this jquery selector

$('input[type=checkbox]:checked').length

this returns the total count of the checkbox selected

just add this event listener which occurs every time a checkbox value is change

$(document).on('change', 'input[type=checkbox]', function() {
    var disabled = $('input[type=checkbox]:checked').length ? false: true;
    $("#search").attr('disabled', disabled);
})

DEMO

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206235

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>

Upvotes: 1

Related Questions