I've got a hidden input field that I want to append text to depending upon what a开发者_JS百科 user enters in two other fields.
So,
<input type="hidden" name="name" value="" />
<input type="text" name="first" value="" />
<input type="text" name="second" value="" />
If the user types First in the first input field and Second in the second input field, I want the name input field to be "First Second"...
Tried using keyup and keypress, but can't get it to append to what's already there?
You could do something like:
var $hidden = $('input[name=name]'),
$first = $('input[name=first]'),
$second = $('input[name=second]');
// bind to keyup and change events on $first and $second
$first.add($second).bind('keyup change', function(e) {
$hidden.val($.trim($first.val()+' '+$second.val()));
});
jsfiddle demo
What exactly are you using this functionality for?
It's probably easier just to extract the data from the two text fields when they're actually being used.
Or instance, just literally append it when whatever the data sent is being sent.
If this happens to be on a form submit, just set a callback.
$("form#id").bind('submit',function() {
name = $("input[name=first]").val() + $("input[name=second]).val()
});
$('input[name=first], input[name=second]').keyup(function() {
var first = $('input[name=first]').val();
var second = $('input[name=second]').val();
$('input[name=name]').val(first + ' ' + second);
});
id them & you can use this as a jumpoff
$('#first, #second').keyup(function(){ $('#hidden').val( $('#first).val() + $('#second').val() ); });
精彩评论