H3llC0d3r
H3llC0d3r

Reputation: 203

jquery not find elements in button area

I have images list and need to select image for album cover.

HTML:

<button type="button" id="imageCover1" class="btn btn-sm btn-success btn-image-cover" data-id="1">
     <i class="far fa-circle"></i> cover
</button>
<input type="hidden" name="is_cover[]" id="imageCover1" class="image-cover" value="">

<button type="button" id="imageCover2" class="btn btn-sm btn-success btn-image-cover" data-id="2">
     <i class="far fa-circle"></i> cover
</button>
<input type="hidden" name="is_cover[]" id="imageCover2" class="image-cover" value="">

JS:

$(document).on('click', '.btn-image-cover', function () {
    var item_id = $(this).attr('data-id');
    $('.image-cover').val('');
    $('#imageCover' + item_id).val('1');
    $('#imageCover' + item_id).find('i').addClass('far fa-check-circle');
});

In action worked and change input value true But when i need to find i and change/add class jquery not find i. how to fix this problem?

Upvotes: 0

Views: 46

Answers (1)

Washington Guedes
Washington Guedes

Reputation: 4365

It actually works.

The problem is that font awesome only renders one icon class. Change the addClass function to toggleClass like this:

$(document).on('click', '.btn-image-cover', function () {
    var item_id = $(this).attr('data-id');
    $('.image-cover').val('');
    $('#imageData' + item_id).val('1');
    $('.btn-image-cover').not(this).find('i').removeClass('fa-check-circle').addClass('fa-circle');
    $(this).find('i').toggleClass('fa-circle fa-check-circle');
});

JSFiddle link

The toggleClass will remove the "fa-circle" class when it is present and add the "fa-check-circle" class if it is not present, and vice-versa.

As noted by @Teemu, you also have same ids with your (button + input:hidden) pairs. I've changed the id of the input:hidden to start with "imageData" instead.

Upvotes: 2

Related Questions