dimanche 2 octobre 2016

Display checkbox name when they are selected

I m trying to implant one function to display name (not value) of checkbox when they are selected. I m on Ruby on Rail app.

So my jquery code is

<script type="text/javascript">
        $(document).ready(function () {
            $('input[name="animaux"]').click(function () {
                getSelectedCheckBoxes('animaux');
            });
            $('input[name="handicap"]').click(function () {
                getSelectedCheckBoxes('handicap');
            });
            $('input[name="television"]').click(function () {
                getSelectedCheckBoxes('television');
            });
            $('input[name="barbecue"]').click(function () {
                getSelectedCheckBoxes('barbecue');
            });
            var getSelectedCheckBoxes = function (groupName) {
                var result = $('input[name="' + groupName + '"]:checked');
                if (result.length > 0) {
                    var resultString = "";
                    result.each(function () {
                        var selectedValue = $(this).val();
                        resultString += groupName + " - "
                            + $('label[for="option-' + selectedValue + '"]').text() + "<br/>";
                    });
                    $('#divfilter').html(resultString);
                }
                else {
                    $('#divfilter').html("");
                }
            };
        });
    </script> 

Filters are displayed with

<div id="divfilter"></div>

And checkbox in rails look like this

<li><p><span class="IcoHandi" aria-hidden="true"></span> Accès handicapé : <%= check_box_tag :handicap, "oui", !!params[:handicap], :class => "handicap" %></p></li>
<li><p><span class="IcoPets" aria-hidden="true" name="skills"></span> Animaux acceptés : <%= check_box_tag :animaux, "oui", !!params[:animaux], :class => "animaux" %></p></li>

Question 1 : When i select one checkbox thats works. But if i select 2 checkbox the first label name is replace by the new one. I want those 2 labels. How i can do that ?

Question 2: Any idea to simplified and DRY this ?

$('input[name="animaux"]').click(function () {
                    getSelectedCheckBoxes('animaux');
                });
                $('input[name="handicap"]').click(function () {
                    getSelectedCheckBoxes('handicap');
                });
                $('input[name="television"]').click(function () {
                    getSelectedCheckBoxes('television');
                });
                $('input[name="barbecue"]').click(function () {
                    getSelectedCheckBoxes('barbecue');
                });

Question 3 : Any idea to implant a cross for "unselect" between the name ?

Thanks for your help !

By the way sorry for my bad english I m french...




Aucun commentaire:

Enregistrer un commentaire