hakki
hakki

Reputation: 6521

When click a button add value to textarea

<script type="text/javascript">

$(document).ready(function() {
     $(".buttons").click(function(){
         var cntrl = $(this).html(); 
         $("#txt-area").text(cntrl+",");

         //alert (cntrl);
     });
});

</script>

When I click to my character on my html page character's value sets to textarea, but when I click to another character previous char disappears. I know about something about arrays in JS but how can I handle this.

How can I add values to textarea properly without disappearing?

enter image description here

Upvotes: 1

Views: 2912

Answers (3)

Kelderic
Kelderic

Reputation: 6687

Arun's answer above works, but it will add a comma to the end. If you want to avoid that, place the comma before the new value, and then have the code check to see if this is the first time something is being added, and not place a comma that time.

$(document).ready(function () {
    var oldvalue;
    var newvalue;
    $(".buttons").click(function () {
        oldvalue = $("#txt-area").val();  //GET THE VALUE OF TEXTBOX WHEN USER CLICKS
        if (oldvalue) {newvalue = ', '+$(this).html();} // IF THE TEXTBOX ISN'T BLANK, PLACE A COMMA BEFORE THE NEW VALUE
        else {newvalue = $(this).html();} //IF THE TEXTBOX IS BLANK, DON'T ADD A COMMA
        $("#txt-area").val(oldvalue + newvalue); //PLACE THE ORIGINAL AND NEW VALUES INTO THE TEXTBOX.
    });
});

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try,

$(document).ready(function() { 
     $(".buttons").click(function(){ 
          var cntrl = $(this).html();
          var xTxtArea = $("#txt-area");
          xTxtArea.text(xTxtArea.text() + cntrl + ","); 
     }); 
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(document).ready(function () {
    $(".buttons").click(function () {
        var cntrl = $(this).html();
        $("#txt-area").val(function (_, val) {
            return val + cntrl + ","
        });

        //alert (cntrl);
    });
});

Demo: Fiddle

or

$("#txt-area").text($("#txt-area").val() + cntrl+",");
$("#txt-area").append(cntrl + ",");

Demo: Fiddle - I prefer using val() because I consider it as a input element

Upvotes: 4

Related Questions