I’d like to have two (or even more) identical html forms on my website.
For example, one – at the top, and another – at the bottom of the page.
What i want is for them to have exactly the same content at any given time. If user changes a value in one of them, all the rest are updated.
Is there a better way to synchronize then javascript onchange/onkeyup events?
onchange fires only after element loses focus.
onkeyup is not perfect too. It wastes a lot of cpu on long text copying and won’t fire if element lost focus between onkeydown and onkeyup events.
I’d like to have two (or even more) identical html forms on my website.
Share
Update: I just learned that HTML5 has a more appropriate event for this,
oninput, but of course it doesn’t work in older browsers.oninputwill detect any kind of text change, includingPaste,Cut, andDeletefrom the right-click menu. So the best option may be to check if the browser supportsoninput(e.g. by using the function recommended here), falling back to the below method if not. On older versions of IE,onpropertychangecan be used to simulateoninput.I decided to change my answer, based on how KnockoutJS accomplishes this. From this page in the Knockout docs:
It accomplishes the asynchronous behavior by using
setTimeoutwith a time value of zero. Other than that, it appears to be just like a regularkeydownevent handler.Here’s a simple example, using jQuery, which I believe behaves equivalently to Knockout’s “afterkeydown” event:
Note:
This will not catch right-click paste events and drag-and-drop events. If you want to update the text on those events too, simply listen for them in the same manner as keydown, e.g.:
Like
keydown,pasteanddropalso need thesetTimeoutin order to update with the latest value of the text.Original answer:
onkeyupis probably the way to go, but you raise a good point about it not firing if the element loses focus between keydown and keyup. Based on this answer, I’m pretty sure the solution would be to listen for the keyup event on a container element (or on the body, although in this case it would probably make the most sense to bind it to the<form>element).As to CPU usage on paste, you could try canceling the event unless a certain amount of time has passed (say 50 ms)…hopefully that will be sufficient. If not, you could look at how some of the popular 2-way data-binding frameworks handle this…most of the ones I’ve seen use
onkeyup.