Why is my checked element null in a helper?


#1

I’m trying to create a helper that returns the checked value (true or false) of a checkbox in order to display or not a select.
However the helper is returning the element as null even though it isn’t and in events it works.

The html:

<input type="checkbox" name="lingua" class="inputLa" unchecked>Yes
        {{#if linguaChecked}}
        <select name="la" class="la">
            <option value="en">English</option>
            <option value="pt">Português</option>
            <option value="fr">Français</option>
            <option value="de">Deutsch</option>
            <option value="es">Español</option>
        </select>
        {{/if}}

The helper:

linguaChecked: function(){
    return document.querySelector(".inputLa").checked;
}

#2

I believe the helpers run before onRendered does, and since that helper isn’t reactive you will get null. My best guess.


#3

I also suggest template scoped reactive var.
And no need to query whole document, just use template scoped html match.


#4

@jrudio You’re right. I tested it with Meteor.setTimeout and it works.
@shock Good point but how can I do it? :blush:


#5

Glad you confirmed it! :thumbsup:

I’m not sure how @shock would do it, but I’d accomplish it like this(May not be a good pattern):

    Template.myTemplate.onCreated(function(){
        this.linguaChecked = new ReactiveVar(null)
    });

    Template.myTemplate.events({
        // Not sure of the exact syntax to listen for changes on an element
        'changed .inputLa': function(event, template){
            var checked = template.$('.inputLa').checked
            template.linguaChecked.set(checked)
        }
    });
    // Same way as above but just initial value, would combine into a function
    Template.myTemplate.onRendered(function(){
        // Get initial value
        var checked = this.$('.inputLa').checked
        this.linguaChecked.set(checked)
    });

    Template.myTemplate.helpers({
        linguaChecked: function(){
            return Template.instance().linguaChecked.get()
        }
    })

#6

Yes, I was refering to template scope matching of $(’.inputLa’) as in example above.
It looks nice.

Maybe initialize that linguaChecked to something else than null based on html would be nice too. But than it need to be changed in both template+helper in case of another default value
If you define it as non-reactive variable and use it in helper, it would not rerun, so it will define just default.
Like

Template.myTemplate.onCreated(function(){
        var defaultChecked = true;
        this.linguaChecked = new ReactiveVar(defaultChecked)
    });

Template.myTemplate.helpers({
  defaultCheckedValue: return defaultChecked;
})

or somethign like that
have fun :smiley: