Reputation: 21
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
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
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