kentor kentor - 1 year ago 86
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:

each account in accounts
div(class='toggle toggle-success', onload='initToggle(#{account.IsActive}, this)')
| #{account.Id}
td #{account.Email}

My init toggle function:

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

My problem:

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

Uncaught ReferenceError: initToggle is not defined

How would I properly initialize my on/off toggles?

Answer Source

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 = $"isActive") === "true";
    // or .data("is-active") for jQuery 2, see
    $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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download