I have a modal box with some fields in there, and based on some values in other fields, they may or may not appear.
So the fields look like
<div class="row">
<select class="form-control" id="ddlNewInputType" placeholder="Enter your input type">
<option value="input">Input</option>
<option value="formula">Formula</option>
</select>
</div>
{{#if isFormula }}
<div class="row">
<input type="text" id="txtNewInputFormula" placeholder="Enter formula">
</div>
{{/if}}
There is a helper that determines whether the txtNewInputFormula textbox is shown
isFormula: ->
return Template.instance().isFormula.get();
isFormula is a ReactiveVar that gets populated when the dropdown list changes
'change #ddlNewInputType': (e,t) ->
isFormula = $(e.currentTarget).val() == 'formula'
t.isFormula.set(isFormula);
In effect, the rule is if the input type = input, don't display the formula field, and if the input type = formula, display the formula field.
When my modal box loads up, it is either for a new or existing object. If it is an existing object, I prepopulate the modal box with values in the database like this
'click #btnEditInput': ->
$('#addInputModal').modal()
$('#txtNewInputName').val(this.name)
$('#txtNewInputFormula').val(this.formula)
$('#ddlNewInputType').val(this.inputType)
$('#ddlNewInputType').change()
The problem is every field except for txtNewInputFormula is being populated. I suspect txtNewInputFormula is not populated because it is inside the handlebar if statement and that hasn't been evaluated yet and therefore, the HTML element does not exist.
How can I get around this? How can I populate a HTML element inside an IF statement?
You're probably correct in your diagnostic, have you tried using handlebars syntax to reactively populate the input text value with appropriate data ?
Something like this :
{{#if isFormula }}
<div class="row">
<input type="text" id="txtNewInputFormula" placeholder="Enter formula" value="{{formula}}">
</div>
{{/if}}
Making the input value into a reactive helper will set it regardless when the DOM element is ultimately created.
Generally speaking, when you find yourself manipulating jQuery to modify the DOM and bypassing Blaze, you may get into trouble.
I agree with @saimeunt, you shouldn't be manipulating the DOM with jQuery like this. You should look at having a wrapper for adding modal templates to the DOM, and providing data.
However, if you wanted to just make your code work, you can.
Basically you want to delay the update to #txtNewInputFormula until after the next flush.
'click #btnEditInput': ->
formula = this.formula
Tracker.afterFlush ->
$('#txtNewInputFormula').val(formula)
return
$('#txtNewInputName').val(name)
$('#ddlNewInputType').val(this.inputType).change()
$('#addInputModal').modal()
return
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With