mardi 13 juin 2017

Limited Checkbox Selection using Array and Javascript

I have a problem in here, I followed someone's instruction but somehow I'm missing something. When I try to test this the checkboxes are still not limited. I maybe missed something or my is wrong.

here's the code named practice_limited_selection.html

            <!DOCTYPE html>
            <html>
            <head>
                <title>Limted Selection</title>
            <script type="text/javascript">
                $(document).ready(function(){
                    $("input[type=checkbox]").click(function(e) {
                        if ($(e.currentTarget).closest("div.question").length > 0){
                            toggleInputs($(e.currentTarget).closest("div.question")[0]);
                        }
                    });
                });

                function toggleInputs(questionElement){
                    if ($(questionElement).data('max-answers') == undefined) {
                        return true;
                    }
                    else
                    {
                        maxAnswers = parseInt($(questionElement).data('max-answers'), 10);
                        if ($(questionElement).find(":checked").length >= maxAnswers) {
                            $(questionElement).find(":not(:checked)").attr("disabled", true);
                        }
                        else
                        {
                            $(questionElement).find("input[type=checkbox]").attr("disabled", false);
                        }
                    }
                }

            </script>
            </head>
            <script type="text/javascript" href="limited.js"></script>
            <body>

            <div class="question" data-max-answers="2">
                <p>Here's a question that is up to 2 answers: <br></p>
                <input type="checkbox" name="answer1[]" value="A"> A <br>
                <input type="checkbox" name="answer1[]" value="B"> B <br>
                <input type="checkbox" name="answer1[]" value="C"> C <br>
                <input type="checkbox" name="answer1[]" value="D"> D <br>
            </div>
            <div class="question" data-max-answers="3">
                <p>Here's a question that is up to 3 answers: <br></p>
                <input type="checkbox" name="answer2[]" value="A"> A <br>
                <input type="checkbox" name="answer2[]" value="B"> B <br>
                <input type="checkbox" name="answer2[]" value="C"> C <br>
                <input type="checkbox" name="answer2[]" value="D"> D <br>
            </div>

            </body>
            </html>




Aucun commentaire:

Enregistrer un commentaire