samedi 10 février 2018

Jquery - Toggle Input text after checkbox

I have this code which works perfectly, It can toggle an input when checkbox is checked.

https://jsfiddle.net/majmo6r4/

But, if one day I want to add more checkboxes, I have to duplicate my code and that's not what I want. I want to improve my code in order to have the same feature with each checkboxes without create another class and duplicate my if statement and variables on my js file.

I had an idea like this :

(function($){
function $test() {
    let $cbs = $(".cbTeam");
    $cbs.each(function () {
        let $inputs = $('.inputTeam');
        if($cbs.siblings().is(':checked')) {
            $inputs.css("display", "flex");
        } else {
            $inputs.css("display", "none");
        }
    });
}
$(this).click($test);
}(jQuery));

For each checkboxes, I can toggle his input, so I need to consider that the checkboxes has the same class name and for the inputs too.

<div class="form-group">
            <label>Jeux - Préférences</label>
                    <div class="checkbox">
                        <label><input type="checkbox" class="cbTeam" value="">Hearthstone</label>
                        <input type="text" class="form-control inputTeam" placeholder="Equipe Hearthstone">
                    </div>
                    <div class="checkbox">
                        <label><input type="checkbox" class="cbTeam" value="">League of Legends</label>
                        <input type="text" class="form-control inputTeam" placeholder="Equipe LoL">
                    </div>
            <button type="submit" class="btn btn-default">S'inscrire</button>
        </div>

Thank you for taking time to my problem, I hope there's enough informations and have a nice day full of code :)

P.S. I want to say "Hello" at the start of the topic but it disappear when i publish the message :(




Aucun commentaire:

Enregistrer un commentaire