mercredi 10 mars 2021

Multiple Checkbox selection results

I have 3 color checkbox's Red Green Blue. My goal is to have a user make a selection and show a unique div ID. E.g. select Red see the #red box. Selecting Red and Green shows the #redgreen box and hides #red and #green etc. There's 8 combinations of the 3 including no-selection (which is default hidden).

I'm very new to JavaScript/jQuery and over the last week I've butchered my attempt. I'm open to all suggestions and lot limited to JavaScript. If you know of a more efficient way to get what I need please share.

$('input[type="checkbox"]').click(function () {
    $('.box').hide();
    if ($('#red').is(':checked')) $('.red.box').show();
    if ($('#green').is(':checked')) $('.green.box').show();
    if ($('#blue').is(':checked')) $('.blue.box').show();    
       
    if ($('#red').is(':checked') && $('#green').is(':checked')) $('.redgreen.box').show() && $('.red.box, .green.box').hide();
    
});
.box {
    padding: 20px;
    display: none;
    margin-top: 20px;
    border: 1px solid #000;
}
.redgreen {
    border: 1px solid black;
}
.red {
    background: #ff0000;
}
.green {
    background: #00ff00;
}
.blue {
    background: #0000ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <label>
        <input type="checkbox" id="red" name="colorCheckbox" value="red">red</label>
    <label>
        <input type="checkbox" id="green" name="colorCheckbox" value="green">green</label>
    <label>
        <input type="checkbox" id="blue" name="colorCheckbox" value="blue">blue</label>
</div>
<div class="red box"><strong>red</strong></div>
<div class="green box"><strong>green</strong></div>
<div class="blue box"><strong>blue</strong></div>

<div class="redgreen box"><strong>red and green</strong></div>



Aucun commentaire:

Enregistrer un commentaire