0

I borrowed some code to make a 3 state button. I'm trying to make one button for each of the vowels. First one does its job, the other ones don't seem to change color. I don't know how to fix this.

I've tried moving the foreach loop up and down but it doesn't seem to do the trick.

@foreach ($vocales as $vocal)
<div class="p-1 d-inline-block">
    <div class="btn-group-toggle d-inline" data-toggle="buttons">
        <input type="radio" name="high" value="2" checked hidden>
        <input type="radio" name="high" value="1" hidden>
        <input type="radio" name="high" value="0" hidden>
        <button type="button" id="toggler" class="btn btn-secondary">{{$vocal}}</button>
    </div>
    <div id='result'></div>

    <script type="text/javascript">
        var $radios = $('input[type="radio"][name="high"]');
        $('#result').html($radios.filter(':checked').val());
        $('#toggler').click(function() {
            var colorClasses = ["btn-danger", "btn-success", "btn-secondary"];
            var $checked = $radios.filter(':checked');
            var $next = $radios.eq($radios.index($checked) + 1);
            if (!$next.length) {
                $next = $radios.first();
            }
            $next.prop("checked", true);
            var newValue = $radios.filter(':checked').val();

            $(this)
            .removeClass(colorClasses.join(" "))
            .addClass(colorClasses[newValue]);

            $('#result').html(newValue);
        });
    </script>
</div>
@endforeach

If you can make this work I'd be extremely grateful

1 Answer 1

1

Each #result must have a unique identifier, for example # result-1 # result-2, etc. In js scripts as well. The error is that the first element is changed and the subsequent ones are ignored.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.