Kwnstantinos Natsios Kwnstantinos Natsios - 14 days ago 4
Javascript Question

jquery checked and unchecked events

I have a problem here with the following code

$('.paron').change(function() {
if($(this).is(":checked")) {
var moduleid = <?php echo $moduleid; ?>;
var studentid = $(this).attr('id');
var weeknum = <?php echo $weeknum; ?>;

undisableTxt(studentid);

}
});


So I take the
id
of a certain
tr
which has an
input
and i send it to a function. All good till now.
But this is happening when the user
check
the
input [checkbox]

when he UNCHECK, how can i have the
id
to send it to another function???

I've tried the following but no luck

$('.paron').change(function() {
if($(this).is(":checked")) {
var moduleid = <?php echo $moduleid; ?>;
var studentid = $(this).attr('id');
var weeknum = <?php echo $weeknum; ?>;

undisableTxt(studentid);

} else {
disableTxt(studentid); //error for undefined variable student id.
}
});


So i get an error for undefined
studentid
. FYI each row has another id.

Answer

The variable 'studentId' doesn't exist in your else block. Also you shouldn't define variables with var in blocks, because var doesn't scope variables at the block level, use let or const for that. I also set $this, to save going back and forth into the DOM for performance.

in jQuery you would do it like this.

$('.paron').change(function() {
  const $this = $(this);  
  const studentid = $this.attr('id');

  if($this.is(":checked")) {
    // removed for brevity, but using let or const
    undisableTxt(studentid);
  } else {
    disableTxt(studentid); 
  }
});