Is it possible to use if condition to check if the radio button is clicked in Underscore templating?

253 Views Asked by At

Is it possible to get the value from a radio button click and create a if condition for the following section? If yes, then how? If not, then how can I accomplish that?

SplitDialog: _.template([
    '<div id="percentage-split-dialog" title="Split by">',
        '<div class="radioContainer">',
            '<span class="radio-container">',
                '<label for="percentage" class="control-label">Percentage</label><input class="hasmatches radio" type="radio" name="hasmatches" value="percentage" id="percentage">',
            '</span>',
            '<span class="radio-container">',
                '<label for="number" class="control-label">Number</label><input class="hasmatches radio"type="radio" name="hasmatches" value="number" id="number">',
            '</span>',
        '</div>',
        '<% if(value==="percentage") { %>',
            '<div class="percentage-split-row">',
                '<input type="text" value="0"/> ',
            '</div>',

        '<% } else { %>',
            '<div class="percentage-balance-row">',
                '<input type="text" disabled="disabled" value="100"/> <span>Remaining Percentage</span>',
            '</div>',
            '<div class="row">',
                '<label><input type="checkbox" id="copyCodingDetails" /> Copy coding details to new lines</label>',
            '</div>',
            '<% } %>',
    '</div>'
].join('')),

Any help would be really beneficial? Thanks!

1

There are 1 best solutions below

1
On BEST ANSWER

No, I don't think you can do what you want to do in any sane way.

When you compile an Underscore template, it is converted to a JavaScript function through simple string manipulation. For example, a simple template like <%= x %> becomes this bit of JavaScript:

function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+=''+
((__t=( x ))==null?'':__t)+
'';
}
return __p;
}

So for a template to know anything about its own content, you'd need that function to be able to parse its own source code and the source isn't even available to the template function when it is executed.

You also can't bind event handlers from inside the template because the template is just text that gets turned into a function, the nodes aren't in the DOM until later so there's nothing to bind to.

You'll have to bind to change events on the radio buttons outside the template and have those handlers manipulate the DOM as needed.