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>
0mpurdy
3,3531 gold badge22 silver badges29 bronze badges
asked Aug 6, 2017 at 12:47
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='' />

answered Aug 6, 2017 at 12:52
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='' />

answered Aug 7, 2017 at 10:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.