Dambo Dambo - 2 months ago 5
HTML Question

How to create a 'only' button for a checkbox menu?

I am trying to make a button 'only' for a checkbox menu that would uncheck everything (within each menu) except the closest checkbox.
enter image description here

I have some code that works, but it's a sort of hack and instead I would like to say in 1 line something like:


  • if $(this).closest('.checkbox').find('input') is
    checked
    then uncheck, else leave as is



Also, I need the event to be fired as the user actually clicked (is it with
triggerHandler
)?



$('.only').on('click', function() {

$(this).closest('.checkbox').find('input').prop('checked', false);
$(this).closest('.row').find('input').prop('checked', true);
$(this).closest('.checkbox').find('input').prop('checked', false);
$(this).closest('.row').find('input').trigger('click');
});

.only {
border: 1px solid rgb(115, 135, 156);
float: right;
border: 1px;
border-radius: 5px;
padding-right: 7px;
padding-left: 7px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<div class="row">
<div class="right">
<div class="only">only</div>
</div>
<label>
<input name="countryOriginMenu" value="Not provided" checked="checked" type="checkbox">
<span>Frist</span>
</label>
</div>
<div class="row">
<div class="right">
<div class="only">only</div>
</div>
<label>
<input name="countryOriginMenu" value="Not provided" checked="checked" type="checkbox">
<span>Second</span>
</label>
</div>
<div class="row">
<div class="right">
<div class="only">only</div>
</div>
<label>
<input name="countryOriginMenu" value="Not provided" checked="checked" type="checkbox">
<span>Third</span>
</label>
</div>

</div>





https://jsfiddle.net/2m0cu795/:

Answer

You trigger the wrong event, use change Remove a duplicate line. NOTE: IF you trigger the "click" it changes the value while "change" does not.

$('.only').on('click', function() {
  $(this).closest('.checkbox').find('input[type="checkbox"]').prop('checked', false);
  $(this).closest('.row').find('input[type="checkbox"]').prop('checked', true).trigger('change');
});

Alternately, you can NOT change the current ones value, whatever its value (the ONLY) one with:

$('.only').on('click', function() {
  var cb = $(this).closest('.checkbox').find('input[type="checkbox"]');
  var me = $(this).closest('.row').find('input[type="checkbox"]');
  cb.not(me).prop('checked', false);
  me.trigger('change');
});

OR do the trigger on the OTHER checkboxes: (since they are the ones changing)

cb.not(me).prop('checked', false).trigger('change');
Comments