4

I have a group of checkboxes as -

<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>

Due to variable values of id and name, I'm unable to handle onclick event on checkbox with label One.

I've tried this which works fine, but I don't want to use check_1 since the number 1 is variable and could be changed.

$("#check_1").change(function() {
  alert('Checkbox One is clicked');
});

How do I do this as I have no access to modify the html ?

Aruna
  • 11,959
  • 3
  • 28
  • 42
jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39

2 Answers2

5

You can use a selector like this $('input[type="checkbox"]:has(+ label:contains("One"))') with the label text as below,

$('input[type="checkbox"]:has(+ label:contains("One"))').on('click', function(){
  alert('Checkbox One is clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>
Aruna
  • 11,959
  • 3
  • 28
  • 42
  • This works fine, is there any cleaner way ? will accept this if I don't find any +1 – jitendrapurohit Dec 06 '16 at 11:37
  • If you want to find the checkbox by the label text then this is the cleaner `jquery` way of selector. If you need to find by any other logic, please let me know and I will update the answer – Aruna Dec 06 '16 at 11:39
  • @jitendrapurohit Performance wise its good as this is using the single selector rather than manipulating the `dom` with multiple selectors – Aruna Dec 06 '16 at 11:45
1

Looks like your only criteria is the text of the label so you could target the input based on that label like :

$('label:contains("One")').prev('input:checkbox').change(function(){
    console.log('One changed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="check_1" name="check[1]" type="checkbox" value="1"/>
<label for="check_1">One</label>&nbsp;

<input id="check_2" name="check[2]" type="checkbox" value="1"/>
<label for="check_2">Two</label>&nbsp;

<input id="check_3" name="check[3]" type="checkbox" value="1"/>
<label for="check_3">Three</label>

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101