获取附加文本区域的值 [英] Get value of appended textarea

查看:117
本文介绍了获取附加文本区域的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本区域附加一个按钮

i append a textarea with a button

$(".mydiv").append("<textarea id='myTextarea'></textarea><div class='sendReply btn btn-default'>my button</div>");

然后,我将新文本写入textarea,并尝试通过单击功能从textarea获取新的写入值;

After that , i'm writing new texts into textarea and trying to get new writed value inside from textarea with this on click function ;

jQuery(document).on('click','.sendReply', function () {
  var myNewText =  $("#myTextarea").val();
    console.log(myNewText);
  });

但是它说这是一个空字符串",如果我添加带有<textarea id="myTextarea">some text</textarea>这样的值的文本区域,我的功能会起作用并给我一些文本",但是如果我编辑textarea并单击sendReply按钮(我单击函数),它仍然给我一些文字",没有变化

But it says that this an "empty string" , if i add text area with a value like <textarea id="myTextarea">some text</textarea> my fucntion works and gives me "some text" but if i edit textarea and click sendReply button (my on click function), it is still gives me "some text" , it don't change

在添加文本区域后,如何获取已编辑的文本区域值?

How can i get edited textarea value after apppend a textarea?

推荐答案

在附加HTML的同时,在.sendReply中有一个.

You have an . in .sendReply while appending the HTML

您只需要从.sendReply

使用

<div class='sendReply btn btn-default'>my button</div>"

当您使用事件委托时,您的jQuery将正常工作.

As you are using Event delegation your jQuery will work.

您要多次添加具有相同ID的文本区域吗? $("#myTextarea").val()将始终显示ID为 myTextarea 的第一个文本区域的值.您可以使用通用类,然后使用 prev() 选择文本区域

As you are adding textarea with same ID multiple times? $("#myTextarea").val() will always show value of first textarea with id myTextarea. You can use a common class and then use prev() to select the textarea

查看示例

$(document).ready(function() {

  $(document).on('click', '.sendReply', function() {
    var myNewText = $(this).prev(".myTextarea").val();
    alert(myNewText);
  });
  for (var i = 0; i < 5; i++) {
    $(".mydiv").append("<textarea class='myTextarea'>some text</textarea><div class='sendReply btn btn-default'>my button</div>");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='mydiv'></div>

这篇关于获取附加文本区域的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆