lundi 26 novembre 2018

Write jquery scripts dinamic

I need to write scripts in jQuery for checkbox's event's dinamically, this is my html code:

<fieldset>
            <label>
                <input type="checkbox" name="radio0" id="radio0">
                <img id="img0" src="web_bg.jpg" width="200" height="200"/>
            </label>
            <label>
                <input type="checkbox" name="radio1" id="radio1">
                <img id="img1" src="web_bg.jpg" width="200" height="200"/>
            </label>
            <label>
                <input type="checkbox" name="radio2" id="radio2">
                <img id="img2" src="web_bg.jpg" width="200" height="200"/>
            </label>
            <label id="label">3</label>
</fieldset>

and this is my jQuery script that works :

$('#radio0').click(function () {
                if ($(this).is(':checked')) {
                    $('#img0').css("opacity", "0.5");
                } else {
                    $('#img0').css("opacity", "1");
                }
            });
            $('#radio1').click(function () {
                if ($(this).is(':checked')) {
                    $('#img1').css("opacity", "0.5");
                } else {
                    $('#img1').css("opacity", "1");
                }
            });
            $('#radio2').click(function () {
                if ($(this).is(':checked')) {
                    $('#img2').css("opacity", "0.5");
                } else {
                    $('#img2').css("opacity", "1");
                }
            });

but i want to put this code in a bucle like this (but this don't works):

var text = $('#label').text();
            var max = parseInt(text);
            for (var i = 0; i < 3; i++) {
                $('#radio' + i + '').click(function () {
                    if ($(this).is(':checked')) {
                        $('#img' + i + '').css("opacity", "0.5");
                    } else {
                        $('#img' + i + '').css("opacity", "1");
                    }
                });




Aucun commentaire:

Enregistrer un commentaire