2

I've had this little problem where I wanted to check all checkboxes inside a specific area with the help of some javascript and a few jquery functions. I retrieved the value of the "select-all" checkbox and wanted to check/uncheck all other checkboxes under it.

Case 1: status = (elt.checked == true); This gives me a string with the value "true" or "false" which, when put into a conditional statement, will always be seen as true since it's not an empty string.

Case 2: const status = (elt.checked == true); This gives me a boolean with the value true or false which can actually be used in the conditional statement.

$(document).on('change', '.select-all input', function(e) {
    elt = e.target;
    status = (elt.checked == true);
    $(elt).closest('.files-list').find('input').each(function(i, e) {
        if (status)
            $(e).attr('checked', true);
        else
            $(e).removeAttr('checked');
    });
});

Why does this const modifier have any influence on the data type of the variable?

Alb
  • 1,063
  • 9
  • 33
  • 3
    Because `window.status` already exists, and can only be a string. (using a different variable name would fix it) – CertainPerformance Feb 19 '19 at 06:39
  • 2
    Why are you using global variables in your function? Did you forget to declare `elt` and `status`? – melpomene Feb 19 '19 at 06:41
  • 2
    You should always use `const` or `let` to declare a variable (or, if you have a good reason, `var`.) In strict mode, your code would not be allowed so the problem wouldn't occur, so using strict mode is a good idea too. – Cat Feb 19 '19 at 06:42
  • @CertainPerformance Thank you a lot for the quick answer, I didn't know that window had this variable :). – Alb Feb 19 '19 at 06:43
  • I think your code boils down to this: `$(document).on('change', '.select-all input', function() { $(this).closest('.files-list').find('input').prop('checked', this.checked); });` – Thomas Feb 19 '19 at 07:02

0 Answers0