简体   繁体   English

单击按钮时,将值添加到文本区域

[英]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. 当我单击我的html页面上的字符时,字符的值设置为textarea,但是当我单击另一个字符时,先前的字符消失了。 I know about something about arrays in JS but how can I handle this. 我对JS中的数组有所了解,但如何处理。

How can I add values to textarea properly without disappearing? 如何正确地将值添加到textarea而不会消失?

在此处输入图片说明

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 演示: 小提琴 -我更喜欢使用val(),因为我认为它是输入元素

Arun's answer above works, but it will add a comma to the end. 上述Arun的答案有效,但最后会加逗号。 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.
    });
});

Try, 尝试,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM