I want to get two values first and last names in one hidden field with space between. I tried with this code
jQuery(document).ready(function($) {
$('input[name="firstname"]').keyup(function() {
$('input[name="fullname"]').val($(this).val());
});
});
jQuery(document).ready(function($) {
$('input[name="lastname"]').keyup(function() {
$('input[name="fullname"]').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="firstname" value="">
<input type="text" name="lasttname" value="">
<input type="hidden" name="fullname" value="">
It is not working how i want. It's showing only one value each time. Can anyone help me with this how can i get this work?
Thanks in advance.
The issue is because you're overwriting the value of the hidden field on every key entry. To fix this you can use a single event handler on both inputs which concatenates the first and lastnames together. Try this:
jQuery(function($) {
var $firstname = $('input[name="firstname"]');
var $lastname = $('input[name="lastname"]');
var $fullname = $('input[name="fullname"]');
$firstname.add($lastname).keyup(function() {
$fullname.val($firstname.val() + ' ' + $lastname.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="firstname" value="" />
<input type="text" name="lastname" value="" /><br /><br />
<input type="text" name="fullname" value="" readonly="true" />
Note that I made the hidden field visible to make the behaviour clearer in the example.
As of now you are overwriting the content of hidden input. You need to create the fullname string and then update the hidden input.
jQuery(document).ready(function($) {
$('input[name="firstname"], input[name="lastname"]').keyup(function() {
var fn = $('input[name="firstname"]'),
ln = $('input[name="lastname"]');
var name = fn.val() + ' ' + ln.val();
$('input[name="fullname"]').val(name)
console.clear()
console.log(name)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="firstname" value="">
<input type="text" name="lastname" value="">
<input type="hidden" name="fullname" value="">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With