I'm dynamically creating a table row full of checkboxes using JavaScript in the function populateParameterTr(parameters)
. In this function, I set an event handler such that when the checkbox is made active, a hidden input field is created in the toggleHidden
function.
What I'm having trouble with is trying to call toggleHidden
to create these hidden input elements after the checkbox is created, ie not in the event handler. Reason being: I want these hidden input fields when the checkboxes are loaded for the first time. From my understanding calling toggleHidden()
results in this
pointing to the global scope.
I've had a look at bind
,call
and apply
to see if this will help like below:
toggleHidden(display, parameterContainer).bind(checkbox);
Can someone advise me if this can be done. I'm looking at this example as an exercise to get my head around using these methods.
Code:
var populateParameterTr = function(parameters) {
var checkboxes = $('<td></td>');
for (var i in parameters) {
var display = parameters[i].display;
var checkbox = $('<input>').attr({
//...
});
var parameterContainer = $('<div></div>').addClass('parameter').append(checkbox);
checkboxes.append(parameterContainer);
toggleHidden(display, parameterContainer).bind(checkbox);
checkbox.on('change', toggleHidden(display, parameterContainer));
}
}
var toggleHidden = function(display, tableDivide) {
return function() {
if (this.checked) {
var hidden = $('<input>').attr({
//......
});
hidden.appendTo(tableDivide);
} else {
$(this).siblings("input[type='hidden']").remove();
}
};
};