Genti Saliu Genti Saliu - 2 months ago 15x
Javascript Question

jQuery: sync two text fields without using val()

My question is similar to this or this question.

However all the answers there use jQuery's

function to copy the value between the fields.

I cannot use
since the source input field will be
and thus will only be able to listen to keyboard events.

I want to capture the keyboard events on a source input field and based on these populate a target text field. Can it be done?

I was hoping something like this would do it, but it doesn't work.


Any ideas?


Your question doesn't make much sense. You say:

the source input field will be readonly and thus will only be able to listen to keyboard events.

... but that doens't make much sense. If it's readonly, you cannot focus the field... meaning you cannot give it keyboard events. Regardless, you can always get and set the value of a field, even if it's readonly or disabled. If you don't want to use jQuery's val() - then use plain JS.

    document.getElementsByClassName('target')[0].value =;

Update: Now I think I understand your question. Your main goal is that you want to modify the color of the caret by hiding the focused field and writing to another field. Not sure why you want to do this as I assure you your users don't care and you run the risk of interfering with the users experience... and as I type this message I don't even notice the color of the caret in Chrome... buuuut, I have a feeling that you still think that your inputs are more special than others. I feel for your users who try and put the cursor at an earlier point in the input to fix a typo... I digress.

Instead of 2 inputs, create a single input, set it's opacity to 0, and write the entire value to a DIV whenever it changes. This has many benefits:

  1. You get many of the default behaviors of the input without actually needing to see it (eg. cursor on hover on desktop, keyboard navigation, etc).
  2. Your form can still do a vanilla submit without needing to copy values or any other javascript weirdness.
  3. Any other code, validation scripts, etc don't need to change - the input is still getting a value and emitting all events.