Search code examples
jquerybackbone.jsthymeleaf

Trigger change event to trigger backbone event


I am prefilling a form (generated from an external script). Using Jquery: $("#first_name_1").val("test");

When submitting the form it says that my input field is empty ..

After some research:

onchange only fires when the user types into the input and then the input loses focus.

I tried every event (everything !): $("#first_name_1").trigger("change"), etc. ..

After some hours I saw that my form is validated with an external script using Backbone.js ... Its minified crap but I now I am here :

        return n.addHandler([{
        selector: "[contenteditable]",
        updateMethod: "html",
        events: ["input", "change"]
    }, {
        selector: "input",
        events: ["propertychange", "input", "change"],
        update: function (e, t) {
            console.log("88");
            e.val(t);
        },
        getVal: function (e) {
            console.log("99");
            console.log(e);
            return e.val();
        }

UPDATE -> Link to the external Backbone.js script

The application is only logging "99" when I type manually some data in the input field. But not when I use Jquery val() function...

So How do I trigger this event in my external backbone file ??

Many thanks for any help ...

PS: I have not any experience in Backbone.js My application is a Spring Boot App. Frontend: Html, Semantic UI, Jquery, Thymeleaf.

UPDATE

I have answered my own answer ..


Solution

  • Ok I have received some code from externs wich works now:

    Instead of

    function preFillForm(){
        var gegevens = {'first_name_1':'test2 ','last_name_2':'test2 ','e-mail_address_3':'[email protected] '};
        for(var id in gegevens){
                $("#" + id).val(gegevens[id]);
                $("#" + id).trigger("change");
        }
    }
    

    I needed to do

    function preFillForm(){
        var gegevens = [[${gegevens}]];
        for(var id in gegevens){
            var input = $("#" + id)[0];         
            input.value = gegevens[id];
            if ("createEvent" in document) {
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("change", true, true);
                input.dispatchEvent(evt);
            }
            else {
                input.fireEvent("onchange");
            }
        }
    }
    

    I do not really understand the difference but I'm glad it's working now.