Jason Z Jason Z - 5 months ago 9
jQuery Question

Dynamically generating value from one input to another input

I am trying to use jQuery to copy my one of my input tags into the other one dynamically.In other words, when a user is typing in the first input, the 2nd input shows what the user is typing(Only when the checkbox is checked).

The second input should only show up when something is entered in the first input and the box is checked

Links to the fiddle:
https://plnkr.co/edit/GI8jWqh6PbMKO7HVhikP?p=preview

This is what I have so far:

<body>
<input type="password" id="firstInput" />
<input type="hidden" id="secondInput" />
<br/>
<input type="checkbox" id='checkbox'/>

<script>
$('#checkbox').change(function(){
if ($(this).prop('checked')) {
$(secondInput).prop('type', 'text');
$(firstInput).on('input', function () {
$(secondInput).val($(firstInput).val());
});
} else {
$(secondInput).prop('type', 'hidden');
}

});
</script>




This kind of work, however, I am facing the following issues:

1.If I default the checkbox to "checked", jQuery will not see a change event, so if I start typing, the 2nd input will not show anything.

2.When I started typing, the 2nd input shows up. If I remove all the content in the firstInput, the secondInput will not go hidden.

3.Kind of similar issue to 2nd question. If I default the checkbox checked attribute to false, if I change it to checked, the hidden input shows up, even i haven't typed in anything.

4.If I leave the checkbox unchecked, then started typing something, if I change the checkbox to checked, the 2nd input will not show what I have typed, because the change() event happened afterwards.

Advise?

Answer

I think this matches what you want.

It simply uses one event handler for both checkbox and master input

  var $check = $('#4').change(updateSlave),
      $slave = $('#secondInput'),
      $master = $('#firstInput').on('input', updateSlave);


  function updateSlave(){
    var showSlave = $master.val() && $check.is(':checked');
    // not sure about value when hidden
    $slave.prop('type', showSlave ? 'text' : 'hidden').val(showSlave ? $master.val() : '')

  }

DEMO