kentor kentor - 4 months ago 14
jQuery Question

Initialize On-Off toggle elements

I have got a table of accounts and I want to be able to toggle them on/off using JQuery toggles. In the beginning I need to initialize the toggles each account (either they one account is set to on or off). I want to do this on page loading.

My Jade template part:

tbody
each account in accounts
tr
td
.col-sm-7.control-label
div(class='toggle toggle-success', onload='initToggle(#{account.IsActive}, this)')
| #{account.Id}
td #{account.Email}


My init toggle function:

script.
jQuery(document).ready(function () {
function initToggle(isActive, element)
{
if (isActive)
element.toggles({'on': true});
else
element.toggles({'on': false});
}


My problem:

If I use
onload=
for my function call I don't get an error at all. If I use the
onclick=
as function call, google chrome shows:


Uncaught ReferenceError: initToggle is not defined


How would I properly initialize my on/off toggles?

Answer

You get the error because the function is declared / scoped inside the "ready" callback. To fix that, I would move the logic and let the javascript decides when init things:

Jade part

div(class='toggle toggle-success', data-is-active='#{account.IsActive}')

Javascript part

jQuery(document).ready(function ($) {
  $(".toggle").each(function () {
    var $this = $(this);
    var isActive = $this.data("isActive") === "true";
    // or .data("is-active") for jQuery 2, see https://api.jquery.com/data/
    $this.toggles({'on': isActive});
  });
});

The jade side uses a html data attribute to store the information and the js side uses it when the document is ready.