Search code examples
jqueryhandlebars.js

Is there any way to run Handlebar Register helper after Handlebars.Compile


I am creating inline editable form using HandleBars template, Everything is working fine but issue is i have some programs in database table and from there all active programs would be brought. Once user clicks to edit the course editable template is brought via GET request and compiled but i have to populate the select dropdown of the all active programs it would do ajax call and bring all the active programs so at this point i do not know how to run the Handlebars RegisterHelper to populate the data and set the selected value to edit the program because the template has been compiled and executed already before ajax call The code i have written is as : This will run and bring the template, after bringing the template it will compile and execute it.

  $(document).on("click", "#span", function () {
            $.get('/User/code/editbasicinfo.html', function (data) {

                $("#editabledata").append(data);
                var source = $("#some-template").html();
                var template = Handlebars.compile(source);
                var data = JSON.parse($('#JsonData').val());
                $("#editabledata").html(template(data));


            })

        });

when everything is compiled and appended it will call the template's document.ready method which is as

$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ViewUserCourse.aspx/getdropdown",
        data: "{}",
        dataType: "json",
        success: function (data) {

            $("#Program").append(data.d);
            Handlebars.registerHelper("selected", function (foo, bar) {                  
                return foo == bar ? "selected" : "";
            });
        },
        error: function (result) {
            alert("Error");
        }
    });

    $('#datashown').hide();     
});

this call will bring this json

 <option {{selected prog '0' }} value='0'>- Select -</option><option {{selected prog 'ABC' }} value='ABC'>ABC</option><option {{selected prog 'DEF' }} value='DEF'>DEF</option>"

at this point i would like to execut RegisterHelper named selected to set the selected value


Solution

  • Just in your template go to jQuery code

    $(document).ready({});
    

    After you get all of the append data you can use jQuery prop function to set the selected value

    $('#<select> option[value="+ data.gender +"]').prop("selected", true);
    

    If you want to use the handlebar for this then you will have to use partial Methods by HandleBar.