How to make two inputfields that show the same data?
So I have one input field that needs to pop up in another place when the user changes a tab and开发者_C百科 presses a button, but I figured tossing the div around would be too much hassle, so is it instead possible to make two input fields but have them display the same input entered by the user?
Or is there an easier way?
Try this. Of course, make sure it is on DOM .ready()
.
$('#input1').blur(function() {
$('#input2').val( this.value );
});
- Use
.blur()
to run the code when the user leaves theinput1
. - Use
.val()
to set the value ofinput2
to thethis.value
ofinput1
.
If you need to work the reverse direction as well, just assign another handler, reversing the inputs.
$('#input2').blur(function() {
$('#input1').val( this.value );
});
EDIT: To deal with multiple inputs, give them all the same class, then use paired IDs.
Like this:
Example: http://jsfiddle.net/m3q4V/
<!-- In tab 1 -->
<input type="text" class="someClass" id="address_1" />
<input type="text" class="someClass" id="city_1" />
<input type="text" class="someClass" id="zip_1" />
<!-- In tab 2 -->
<input type="text" class="someClass" id="address_2" />
<input type="text" class="someClass" id="city_2" />
<input type="text" class="someClass" id="zip_2" />
js:
$('.someClass').blur(function() {
var parts = this.id.split('_'); // separate into parts, like 'address' and '2'
var num = (parts[1] == 2) ? 1 : 2; // invert the number between 1 and 2
// build the selector with 'address' + '_' + '1'
$('#' + parts[0] + '_' + num).val( this.value );
});
See Working Example
If you want to happen that when first text box loses focus, you need to use blur
event:
$('#textbox1_id').blur(function(){
$('#textbox2_id').val(this.value);
});
精彩评论