Reputation: 243
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:
<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());
});
Upvotes: 0
Views: 4755
Reputation: 21680
Omit [0][value]
as in:
$('input[name=field_firstname]') // removed [0][value]
Not entirely sure why you put that in there.
Also, you might want to use .blur()
instead of .keyup()
, saves you a lot of redundant repetition. Even better, concat the fields on a .submit()
because thats when you care about it anyways. Think about it, "Jhon Doe" means 16 lookups and 8 concatenations when using .keyup()
along with jQuery processes to get it done.
addendum
Seeing this a few times now, people put invalid/problematic characters inside id attributes like [0][value]
, this is invalid to jQuery as it recognises it as a css expression rather then part of an id. document.getElementById( "bla[0]" );
does seem to work however so if you really have to (or are too lazy to fix it), you can do the following:
$( document.getElementById( "bla[0][value]" ) ) //etc
Upvotes: 0
Reputation: 19933
Perhaps I'm missing some context, but I don't think you can use attribute selectors like that. To get at the firstname field, you'd say: input[name='firstname']
.
You're also doing the same thing twice, which is always a good reason to give things some extra thought. For example, you can do both keyup
s in one shot:
$("input[name='firstname'], input[name='lastname']").keyup(...);
You can make things a lot easier by using IDs, though. For example, take this HTML:
<input type="text" name="firstname" id="firstname" value="John John" />
<input type="text" name="lastname" id="lastname" value="Doe" />
<input type="hidden" name="name" id="sanitized_name" value="john-john-doe" />
You'd use the following code snippit:
$('#firstname, #lastname').keyup(function() {
var fullname = $('#firstname').val() + ' ' + $('#lastname').val();
$('#sanitized_name').val(fullname.replace(/\s/g, '-').toLowerCase());
});
Upvotes: 3