Why doesn't this jQuery focusout and change function work?

3.1k views Asked by At

This must be simple, but I can't see what is preventing this combonation .focusout and .change function from working.

I want the first input to copy to the second when the focus leaves the first input. No errors in the console. Fiddle: https://jsfiddle.net/fh8t6mm0/

The reason I want to use focusout is that the .change and .val function doesn't work reliably for some reason.

HTML:

<div id="focusoutdiv">

  <input class="fieldone" type="text">

  <input class="fieldtwo" type="text">

</div>

JS:

$('#focusoutdiv').focusout(function() {
  $('.fieldone').change(function() {
    $('.fieldtwo').val($(this).val());
  });
});
2

There are 2 answers

2
programtreasures On BEST ANSWER

You can also use blur event to copy text from one textbox to other. Below code mightbe helpful for you

$('.fieldone').blur(function() {
    $('.fieldtwo').val($(this).val());
});
2
John R On

Do not use the change event inside focusout event. Because, they need to be defined separately to work as expected. Moreover in your code snippet, change event alone enough to achieve your requirement. Please refer the following example.

$('.fieldone').change(function() {
  $('.fieldtwo').val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="focusoutdiv">
  <input class="fieldone" type="text">
  <input class="fieldtwo" type="text">
</div>