Thomas
Thomas

Reputation: 21

Combine Multiple Input Fields into One Input Field with Javascript?

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>

Upvotes: 1

Views: 4529

Answers (2)

vicky patel
vicky patel

Reputation: 705

$(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='' />

Upvotes: -1

user2575725
user2575725

Reputation:

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='' />

Upvotes: 4

Related Questions