Search code examples
javascriptphpaddclassremoveclasssiblings

siblings.removeclass doesn't work on image


I copy/paste this code form another page on my website. On the first page everything works just fine, somehow it doesn't on the second page...

I'm trying to create a custom radio button function. The page shows images (loaded from my database, using mysqli_fetch_array). The user can click on these images. Once the user clicks on an image, I want javascript to apply another class to this image. If the user clicks another image, I want to restore the class of the first image and apply the class to the latest clicked image.

What I have:

Script

$(window).load(function(){
    $('.bedragbol').click(function() {
        var bedragid = $(this).data("bedragid");
        $(this).addClass('bedragbol_select').siblings().removeClass('bedragbol_select');
        document.getElementById("kosten").value = bedragid;
    });
});

PHP

<table width="100%">
<? while($rows_bedrag=mysqli_fetch_array($sql_bedrag,MYSQLI_ASSOC)){ ?>
<tr>
<td class="img_programmaker_dag">
<img src="../images/<? echo $rows_bedrag['url']; ?>.png" data-bedragid="<? echo $rows_bedrag['id']; ?>" class="bedragbol"> 
</td>
<td>
<font class="txt_programmaker_dag">
<? echo $rows_bedrag['omschrijving']; ?>
</font>
</td>
</tr>
<? } ?>
</table>
<br><br>
<input type="text" id="kosten" name="kosten">

I've added the input field to see if the function is working. The value's updated everytime I click the image. This works fine. Just the css part is not working like it should. Right now it does apply a class when clicked, it just doesn't remove all siblings when another image's clicked. It keeps the selected class. So if I click all images, all images keep their selected class.

What am I missing? What do I need to adjust to remove the class to all siblings, except for the one that's clicked?


Solution

  • try this code if you are not using .bedragbol class in any other element

    $('.bedragbol').click(function() {
      var bedragid = $(this).data("bedragid");
      $('.bedragbol').removeClass('bedragbol_select');
      $(this).addClass('bedragbol_select')
      document.getElementById("kosten").value = bedragid;
    });
    

    Otherwise try this

    $('.bedragbol').click(function() { 
      var bedragid = $(this).data("bedragid"); 
      $(this).siblings().removeClass('bedragbol_select'); 
      $(this).addClass('bedragbol_select') 
      document.getElementById("kosten").value = bedragid;
    });