-1

How to programmatically click checkbox with jQuery? I want to make a hidden checkbox which is checked when user clicks particular element, but my code doesn't work and I have no idea why.

Here's what I tried JSFiddle

code:

//HTML
<input type='checkbox'>
<a href='#' class='click_me'>click me</a>

//js
$('.click_me').click(function(){
    console.log('click');
    $(this).closest('input[type="checkbox"]').toggle();
})
Daniil
  • 133
  • 2
  • 11
  • `.closest()` will get you the closest *parent* element but you want to refer to a sibling element. Try `.prev('input')` instead. – Carsten Massmann Apr 13 '21 at 17:35
  • Does this answer your question? [Setting "checked" for a checkbox with jQuery](https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery) – freedomn-m Apr 13 '21 at 17:35
  • The existing question answers your question as asked, but looks like that may not be the issue you have, given @cars10m comment – freedomn-m Apr 13 '21 at 17:36
  • Does this answer your question? [How do I select a sibling element using jQuery?](https://stackoverflow.com/questions/7463242/how-do-i-select-a-sibling-element-using-jquery) – ikiK Apr 13 '21 at 17:37

1 Answers1

0
  1. Use prev to get a previous sibling.
  2. Use click to click the checkbox.

$('.click_me').click(function(){
    console.log('click');
    $(this).prev('input[type="checkbox"]').click();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox'>
<a href='#' class='click_me'>click me</a>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Thank you very much for your answer! But what if checkbox and link are placed in different containers? – Daniil Apr 13 '21 at 17:39
  • @Daniil Then you need to change the selector based on your HTML structure. – Unmitigated Apr 13 '21 at 17:39
  • The problem is that there are few similar structures on the page. That's why setting class or id for checkbox is not a solution, and it would be better to somehow find closest and click it – Daniil Apr 13 '21 at 17:42
  • @Daniil What does your HTML look like? `closest` is not necessary the correct method. – Unmitigated Apr 13 '21 at 17:42
  • "closest" has a specific meaning - you're using it to mean "nearest located in the html" or "on the page" - that's not what "closest" means in this context. Your question asks specifically about setting the check (or clicking the checkbox) rather than how to find a "matching" checkbox - you might like to ask a new question (as this one has now been answered) with the **specific question that you want answered** – freedomn-m Apr 13 '21 at 17:47
  • @freedomn-m Thank you for your advice! I will try it – Daniil Apr 13 '21 at 18:58