-1

First of all I do not have HTML control. I have mistake in the for loop somewhere as if I do just for one id it works fine.

for (var i = 1; i < 73; i++) {
  $("#a" + i).click(function() {
    if ($("#a" + i).hasClass("green")) {
      $("#Q15v2_" + i).prop('checked', true);
    } else {
      $("#Q15v2_" + i).prop('checked', false);
    }
  });
}
j08691
  • 204,283
  • 31
  • 260
  • 272
Zygimantas
  • 553
  • 8
  • 22

1 Answers1

1

try this and let me know :
check this https://jsfiddle.net/shantaram/g1x7rh25/

$("p[id^=a").click(function() {   // paragraph id start with 'a'
    var len = $(this).prop('id').length;    // calculate id length
    var i = $(this).prop('id').substr(1,len);  // remove 'a' from id to get number
    if ($(this).hasClass("green")) {
        $("#Q15v2_" + i).prop('checked', true);
    } else {
        $("#Q15v2_" + i).prop('checked', false);
    }
});
Shantaram Tupe
  • 1,646
  • 3
  • 16
  • 42
  • 1
    Minor tweak: `if ($("#a" + i).hasClass("green")) {` can be `if ($(this).hasClass("green")) {` – freedomn-m Jan 20 '17 at 14:49
  • thanks for correction, I copy pasted @ Zygimantas Kairys's code also no need of `else` until we manually checks it (p with no `green` class) – Shantaram Tupe Jan 20 '17 at 14:50
  • You can go to the nth degree with improving this - that one seemed the most beneficial without changing too much of the original code. – freedomn-m Jan 20 '17 at 15:10
  • shantaram_t, I think I got it working just I have changed "p[id^=a" to '[id*="a"]' – Zygimantas Jan 20 '17 at 15:14