Search code examples
javascriptjquery

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>

Solution

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