n00b0101
asked on
jquery - set value of hidden input field based on values of text fields
I have three form fields: name, first name, and lastname. The name field is hidden and I'm trying to set the value to the firstname + lastname on keypress. I'm also trying to format it so that the characters are all lowercase and spaces are transformed into dashes.
So:
I've been trying to use the following code, but it's not working...
So:
<input type="text" name="firstname" value="John John" />
<input type="text" name="lastname" value="Doe" />
<input type="hidden" name="name" value="john-john-doe" />
I've been trying to use the following code, but it's not working...
$('input[name=field_firstname[0][value]]').keyup(function() {
var firstname = $('input[name=field_firstname[0][value]]').val();
var lastname = $('input[name=field_lastname[0][value]]').val();
$('input[name=name]').val(firstname.replace(/\s/g, "-").toLowerCase()+lastname.replace(/\s/g, "-").toLowerCase());
});
$('input[name=field_lastname[0][value]]').keyup(function() {
var firstname = $('input[name=field_firstname[0][value]]').val();
var lastname = $('input[name=field_lastname[0][value]]').val();
$('input[name=name]').val(firstname.replace(/\s/g, "-").toLowerCase()+lastname.replace(/\s/g, "-").toLowerCase());
});
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi,
It might be better to use .blur() instead of .keyup, then you are running your code a lot less, and blur will get called whenever that field loses the focus...
plus unless for some reason you can't do it, it would be good to give your input boxes an id and use that to find them. I believe id is technically a required attribute anyway.
It might be better to use .blur() instead of .keyup, then you are running your code a lot less, and blur will get called whenever that field loses the focus...
plus unless for some reason you can't do it, it would be good to give your input boxes an id and use that to find them. I believe id is technically a required attribute anyway.
<script type="text/javascript">
$(document).ready(function() {
$('#firstname,#lastname').blur(function() {
frst = $('#firstname').val().toLowerCase().replace(/ /g,'-');
lst = $('#lastname').val().toLowerCase().replace(/ /g,'-');
$('#name').val(frst + "-" + lst);
alert($('#name').val());
});
});
</script>
Open in new window