Pedram
Pedram

Reputation: 16615

jQuery - Append each input value to one

I have some text box, for example 4 inputs, I want to append each value to one certain text box with comma on KeyUp function beside default value but problem is it will overwrite value with previous value.

want something like this:

01115468852, 234324234, 423423113345, 43341889955

var curval = $('#PhoneTextbox').val();

$('.tag').each(function() {
  $(this).keyup(function() {
    var tags = $(this).val();
    $('#PhoneTextbox').attr('value', curval + " , " + tags);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="PhoneTextbox" value="01115468852" type="text" />
<br />
<br />
<br />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />

Upvotes: 0

Views: 1751

Answers (4)

Ravinder Gujiri
Ravinder Gujiri

Reputation: 1524

use this javascript code

var p = $("#PhoneTextbox").val();
$(function(){
    $('.tag').keyup(function(){
        var t = [];
        t.push(p);
        $('.tag').each(function(i,e){
            if($(e).val().length > 0){
                t.push($(e).val());
            }
        });
        $("#PhoneTextbox").val(t.join());
    });
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388416

You can do something like

var curval = $('#PhoneTextbox').val();

var $tags = $('.tag').keyup(function() {
  var tags = $tags.map(function() {
    return this.value || undefined
  }).get();
  tags.unshift(curval)

  $('#PhoneTextbox').val(tags);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="PhoneTextbox" value="01115468852" type="text" />
<br />
<br />
<br />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />
<input class="tag" value="" type="text" />

Upvotes: 3

Sathish
Sathish

Reputation: 2460

use .change() instead of .keyup()

   $('.tag').each(function () {
$(this).change(function () {
    var tags = $(this).val();
    var curval = $('#PhoneTextbox').val();
    $('#PhoneTextbox').attr('value', curval + " , " + tags);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="PhoneTextbox" value="01115468852" type="text"/>
<br />
<br />
<br />
<input class="tag" value="" type="text"/>
<input class="tag" value="" type="text"/>
<input class="tag" value="" type="text"/>
<input class="tag" value="" type="text"/>

Upvotes: 2

Alex Tartan
Alex Tartan

Reputation: 6836

Try this:

$('.tag').each(function () {
    $(this).keyup(function () {
        var tags = $(this).val();
        var curval = $('#PhoneTextbox').val();
        $('#PhoneTextbox').attr('value', curval + " , " + tags);
    });
});

This way you add it at the end of the last added value

Upvotes: 1

Related Questions