How would you go about updating a form template (handlebars) each time the data updates and keep the input element focused? In my code sample you will find a form field to which is attached a keyup event listener that updates the data.
But on each update I am re-rendering the form which causes the input to lose focus.
JavaScript
import "./styles.css";
import $ from "jquery";
import Handlebars from 'handlebars';
const updateHtml = data => {
const app = $('#app');
const html = template(data);
app.html(html);
}
const app = $('#app');
const data = {
foo: 'default value',
}
const template = Handlebars.compile(`<form><input type="text" id="foo" value="{{foo}}"></form>`);
updateHtml(data);
app.on('change keyup', function(e){
const val = $(e.target).val();
data.foo = val;
updateHtml(data);
});
I have created a codesandbox for you to test https://codesandbox.io/s/magical-leftpad-ry2lx?file=/src/index.js
Try typing in the input and you will find it loses focus after a keyup. So, how to solve this problem so that I can write in the input and the data object updates itself according to the inbox?
Update
I would like to provide more context on the actual application I am developing. I cam creating a complex form that includes, checkboxes, radio buttons, repeater fields which changes inputs depending on another input (conditional fields).
I do not want to update dom elements (adding/inserting/removing) by event listeners. Dom should update when data updates. That is why I am using handlebars templating system.