Marking a checkbox as selected

Asked

Viewed 65 times

-3

I have a list of filters with checkbox on a page and wanted one of those selections to be marked as active by clicking on a banner that will be inside that page.

Example:

<img src="fakeurl.com" alt="Teste">  <label class="sr_teste" title="Teste" 
 index="0" style="display: flex;"><input rel="fq=specificationFilter_x:Teste" 
 class="multi-search-checkbox" type="checkbox" name="Teste" 
 value="Teste">Teste</label>

Is there any way to do this checkbox be selected by clicking on the image ?

  • you can use a jquery/javascript function... I believe your doubt is the same as that link. The difference you will call in the banner onclick. https://answall.com/questions/17713/marcar-desmarcar-checkbox-a-parti-de-um-bot%C3%A3o I hope I helped. Anything, you can call!

1 answer

1


First you need to create a collection of the images (which you call "banner") by placing a class on them (e.g.. class="banners"):

<img class="banners" src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" alt="Teste">

Then you create onclick events in each image with the class:

const banners = document.querySelectorAll(".banners");
for(let banner of banners){
   banner.onclick = function(){
      let alt = this.alt;
      let box = document.querySelector("[type='checkbox'][value='"+alt+"']");
      box.checked = !box.checked;
   }
}

You need to link an image to a checkbox. In the above case I used the attribute alt of the image with the attribute value from the checkbox, since the value should be unique, i.e., the alt image should be exactly the same as the value of the linked checkbox.

The line box.checked = !box.checked; check/uncheck the checkbox every click on the image.

Example:

const banners = document.querySelectorAll(".banners");
for(let banner of banners){
   banner.onclick = function(){
      let alt = this.alt;
      let box = document.querySelector("[type='checkbox'][value='"+alt+"']");
      box.checked = !box.checked;
   }
}
.banners{
   width: 50px;
   height: 50px;
}
<img class="banners" src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg" alt="Teste">  <label class="sr_teste" title="Teste" index="0" style="display: flex;"><input rel="fq=specificationFilter_x:Teste" class="multi-search-checkbox" type="checkbox" name="Teste" value="Teste">Teste</label>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.