Display value from only checked checkbox and if other checkboxes are checked uncheck them

Viewed 176

Lets say that I have 3 checkboxes:

<input type="checkbox" value="25,99" name="price">
<input type="checkbox" value="15,99" name="price">
<input type="checkbox" value="10,99" name="price">

and I want to display the value of the checked checkbox in a div, but only one checkbox can be active at a time.

I was trying to marry these two examples together but this seams kinda messy and overkill:

only one checked at the time http://jsfiddle.net/MQM8k/

$('input.example').on('change', function() {
    $('input.example').not(this).prop('checked', false);  
});

with this link to live

    $(document).ready(function() {
        $("button").click(function(){
            var favorite = [];
            $.each($("input[name='sport']:checked"), function(){            
                favorite.push($(this).val());
            });
            alert("My favourite sports are: " + favorite.join(", "));
        });
    });

Thanks

3 Answers

An easy way is to uncheck all the checkboxes as the first thing you do upon detecting a click, and then re-check the one you are on.

$('.prx').click(function(){
   $('.prx').prop('checked', false);
   $(this).prop('checked', true);
   let prx = $(this).val();
   $('#msg').text(prx);
});
#msg{margin-top:20px;padding: 10px; background:wheat;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
25.99 <input type="checkbox" class="prx" value="25,99" name="price"><br>
15.99 <input type="checkbox" class="prx" value="15,99" name="price"><br>
10.99 <input type="checkbox" class="prx" value="10,99" name="price"><br>
<div id="msg"></div>

$(document).on("click", ".prx", function (){
var self = $(this);
   $('.prx').not(self).prop('checked', false);
   self.prop('checked', true);
   alert(self.val());
});

You should really consider making this input a radio button.

You're essentially breaking the UX of checkboxes to not allow multiple selections. Radio button inputs do this behavior (one selection at a time) by default, will have expected tab actions for accessibility users and won't need all this extra JS.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Related