Reputation: 2177
I have 3 textboxes, I want to create something like this: When I type to textbox1, it will duplicate to textbox3, and when I type to textbox2, it will append to textbox3 with a delimiter ( - ).
For example, if I write STACK to textbox1, textbox3 will result STACK, then if I wrote down textbox2 with OVERFLOW, textbox3 value is: STACK-OVERFLOW
Here's my code at fiddle:
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value);
});
$("#text2").keyup(function() {
$('#text3').val.append('-'+this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="text" id="text3" />
Anyone can fix my code?
Upvotes: 0
Views: 97
Reputation: 453
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value);
});
$("#text2").keyup(function(e) {
$('#text3').val(function(index, val) {
return $("#text1").val() + "-" + e.target.value;
});
});
});
This should do it
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="text" id="text3" />
Upvotes: 1
Reputation: 4747
You need to check also if text2 is empty so you don't have to concatenate the '-' in that case.
$(function() {
$("#text1").keyup(function() {
var text2 = $('#text2').val();
var temp = $(this).val();
if (text2 != '') {
temp = $(this).val()+'-'+text2;
}
$('#text3').val(temp);
});
$("#text2").keyup(function() {
var temp = $('#text1').val()+'-'+$(this).val();
$('#text3').val(temp);
});
});
Upvotes: 1
Reputation: 1720
This is one way to do it: http://jsfiddle.net/6qojd9L4/
$(function() {
$("#text1").keyup(function() {
$('#text3').val(this.value + '-' + $('#text2').val());
});
$("#text2").keyup(function() {
$('#text3').val($('#text1').val() + '-'+this.value);
});
});
Upvotes: 0
Reputation: 24001
$(function() {
var text1value , text2value;
$("#text1").keyup(function() {
text1value = $(this).val();
$('#text3').val(text1value);
});
$("#text2").keyup(function() {
text2value = $(this).val();
$('#text3').val(text1value+'-'+text2value);
});
});
Upvotes: 2