Ошибка с событием Jquery click и проверено - PullRequest
0 голосов
/ 04 октября 2019

У меня есть два флажка с соответствующей меткой, которая имитирует кнопку. Когда я нажимаю на ярлык, он работает, флажок успешно установлен, но мне нужно изменить изображение ярлыка, если флажок установлен или нет. Это работает со второй, но первая кнопка прослушивается и меняет свое изображение только один раз.

Здесь HTML:

<form action="" method="post" class="form-checkboxes">
    <input type="checkbox" name="primero" id="primero" class="checkbox" hidden>
    <label for="primero" class="label-button">
        <img src="img/unchecked.png" width="30px" height="30px" class="img-label">
        Primero
    </label>

    <input type="checkbox" name="segundo" id="segundo" class="checkbox" hidden>
    <label for="segundo" class="label-button">
        <img src="img/unchecked.png" width="30px" height="30px" class="img-label">
        Segundo
    </label>
 </form>

Код CSS:

.form-checkboxes{
    margin-top: 40px;
}
.label-button{
    padding: 8px 10px;
    margin: 10px;
    border: 1px #1f1f1f solid;
    border-radius: 3px;
    cursor: pointer;
    font-family: Arial, Helvetica, sans-serif; /*Aquí pon la que quieras xd*/
    display: inline-flex;
    align-items: center;
}

.label-button:hover{
    box-shadow: 1px 1px 8px #808080;
    background: #d1ff8b;
    transition: all 300ms ease-in-out;
}

.form-checkboxes input[type="checkbox"]:checked + .label-button{
    background: #b3ff41;
    transition: all 300ms ease-in-out;
    box-shadow: 1px 1px 8px #a4ff8d;
    border: 2px #9ffa17 solid;
    outline-color: #808080;
}

И код Jquery:

$(document).ready(function () {
    //Links de las imagenes
    const uncheckedLink = 'img/unchecked.png';
    const checkedLink = 'img/x.png';

    //Labels
    var labels = $('.label-button');

    //Botones
    var checkboxes = $(".checkbox");

    labels.each(function (index) { 
        $(this).click(function () {
            //imagen que se usará
            var imagenesLabel = $(this).find('img');

            //Se determina si el checkbox seleccionado está checked o no
            checkboxes.each(function (index) { 
                if($(this).prop("checked") == true){
                    imagenesLabel.each(function (index) { 
                        $(this).attr('src', uncheckedLink);
                    });
                } else if($(this).prop("checked") == false){
                    imagenesLabel.each(function (index) { 
                        $(this).attr('src', checkedLink);
                    });
                }
            });
        });
    });
});

Ответы [ 2 ]

1 голос
/ 04 октября 2019

Использовать change событие, когда вы ставите / снимаете флажки .. Вот рабочий код ...

$(document).ready(function () {
  const uncheckedLink = 'http://pluspng.com/img-png/png-wrong-cross-cancel-cross-exit-no-not-allowed-stop-wrong-icon-icon-512.png';
  const checkedLink = 'https://img.pngio.com/check-mark-clip-art-check-vector-png-download-540599-free-check-png-900_600.jpg';

  $('.checkbox').on('change', function(){

    if($(this).is(":checked")){
      $(this).next('label').find('img').attr('src', checkedLink);
    }
    else{
      $(this).next('label').find('img').attr('src', uncheckedLink);
    }
  })

});
.form-checkboxes{
    margin-top: 40px;
}
.label-button{
    padding: 8px 10px;
    margin: 10px;
    border: 1px #1f1f1f solid;
    border-radius: 3px;
    cursor: pointer;
    font-family: Arial, Helvetica, sans-serif; /*Aquí pon la que quieras xd*/
    display: inline-flex;
    align-items: center;
}

.label-button:hover{
    box-shadow: 1px 1px 8px #808080;
    background: #d1ff8b;
    transition: all 300ms ease-in-out;
}

.form-checkboxes input[type="checkbox"]:checked + .label-button{
    background: #b3ff41;
    transition: all 300ms ease-in-out;
    box-shadow: 1px 1px 8px #a4ff8d;
    border: 2px #9ffa17 solid;
    outline-color: #808080;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" class="form-checkboxes">
    <input type="checkbox" name="primero" id="primero" class="checkbox" hidden>
    <label for="primero" class="label-button">
        <img src="http://pluspng.com/img-png/png-wrong-cross-cancel-cross-exit-no-not-allowed-stop-wrong-icon-icon-512.png" width="30px" height="30px" class="img-label">
        Primero
    </label>

    <input type="checkbox" name="segundo" id="segundo" class="checkbox" hidden>
    <label for="segundo" class="label-button">
        <img src="http://pluspng.com/img-png/png-wrong-cross-cancel-cross-exit-no-not-allowed-stop-wrong-icon-icon-512.png" width="30px" height="30px" class="img-label">
        Segundo
    </label>
</form>
1 голос
/ 04 октября 2019

Оберните checkbox внутри тега label (этот флажок будет включен / выключен при нажатии на ярлык) и используйте $(this).find('.checkbox').prop("checked"), чтобы определить, является ли checkbox значение on or off, затем измените изображение.

$(document).ready(function () {
    const uncheckedLink = 'https://media.giphy.com/media/5NPhdqmyRxn8I/giphy.gif';
    const checkedLink = 'https://ssl.gstatic.com/images/branding/googleg/2x/googleg_standard_color_64dp.png';
    $('.label-button').click(function () {
      if($(this).find('.checkbox').prop("checked")){
           $(this).find("img").attr('src', uncheckedLink);
         } else { 
           $(this).find("img").attr('src', checkedLink);
        }
    });
});
.form-checkboxes{
    margin-top: 40px;
}
.label-button{
    padding: 8px 10px;
    margin: 10px;
    border: 1px #1f1f1f solid;
    border-radius: 3px;
    cursor: pointer;
    font-family: Arial, Helvetica, sans-serif; /*Aquí pon la que quieras xd*/
    display: inline-flex;
    align-items: center;
}

.label-button:hover{
    box-shadow: 1px 1px 8px #808080;
    background: #d1ff8b;
    transition: all 300ms ease-in-out;
}

.form-checkboxes input[type="checkbox"]:checked + .label-button{
    background: #b3ff41;
    transition: all 300ms ease-in-out;
    box-shadow: 1px 1px 8px #a4ff8d;
    border: 2px #9ffa17 solid;
    outline-color: #808080;
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<form action="" method="post" class="form-checkboxes">
    <label for="primero" class="label-button">
        <input type="checkbox" name="primero" id="primero" class="checkbox" hidden>
        <img src="https://ssl.gstatic.com/images/branding/googleg/2x/googleg_standard_color_64dp.png" width="30px" height="30px" class="img-label">
        Primero
    </label>
    <label for="segundo" class="label-button">
        <input type="checkbox" name="segundo" id="segundo" class="checkbox" hidden>
        <img src="https://ssl.gstatic.com/images/branding/googleg/2x/googleg_standard_color_64dp.png" width="30px" height="30px" class="img-label">
        Segundo
    </label>
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...