1

I have this code below which combines multiple fields into one field however it only combines them when you click a button. Is there a way to edit this so that it does not require a button to be clicked in order to combine the fields and just combines them as the user types?

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>    

    First Name: <input class="combine" id="input1"  value=""/>
    Last Name: <input class="combine" id="input2" value=""/>
    <button id="setVal">Combine</button>
First and Last Name Combined <input class="combine" id="Voltes5" size="105" value='' />

    <script type="text/javascript">
    $('#setVal').click(function(){
    $('#Voltes5').val(
      $('.combine')
      .not('#Voltes5')
      .map(
        function(){
          return $(this).val();
        })
      .get()
      .join('')
    );
    });
      </script>
2
  • Sure, just listen to another event, like $('.combine').on('input', …). Commented Aug 6, 2017 at 12:51
  • Can you provide a working example based on my code above? Sorry I am new to JS and a bit lost on what you mean. Commented Aug 6, 2017 at 12:53

2 Answers 2

4

Use input event.

$(function() {
  $('#input1, #input2').on('input', function() {
    $('#Voltes5').val(
      $('#input1, #input2').map(function() {
        return $(this).val();
      }).get().join(' ') /* added space */
    );
  });
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

First Name: <input class="combine" id="input1" value="" /> Last Name: <input class="combine" id="input2" value="" />First and Last Name Combined <input class="combine" id="Voltes5" size="105" value='' />

Sign up to request clarification or add additional context in comments.

Comments

-1

$(document).ready(function(){
$("#setVal").click(function(){
$("#Voltes5").val($("#input1").val() + " " + $("#input2").val());
});
	});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    First Name: <input class="combine" id="input1"  value=""/>
    Last Name: <input class="combine" id="input2" value=""/>
    <button id="setVal">Combine</button>
First and Last Name Combined <input class="combine" id="Voltes5" size="105" value='' />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.