如何使用jQuery将文本字段中的文本读取到变量中

How to read text from textfield using jQuery to the variable?

本文关键字:文本 变量 读取 字段 何使用 jQuery      更新时间:2023-09-26

因此,我在本地服务器上获得了该页面,该页面包含文本区域和按钮。我正在尝试给按钮写onclick函数,它可以读取我在文本区键入的任何内容,并将记录写入数据库。就像我在这里输入完问题后,按Ask question。问题是,我无法正确阅读文本区域中的文本,它基本上只看到加载页面时的内容,然后重写它。我应该如何获取我在点击按钮前键入的文本?我只想知道如何将该文本复制到某个var中,然后将其放入数据库。

$.getJSON('/link/' + tenderId, function (data) { 
     var description = ''; 
     description += '<textarea id="description" class="form-control" rows="3">' + data.description + '</textarea>'; 
     $('#description').html(description); 
});

在点击事件中使用此代码

var textareaValue = $('textarea#textareaId').val();

html

<textarea id="textareaId"></textarea>

SO回答:https://stackoverflow.com/a/144836/2772017

您需要使用val()(我猜您正在使用text()(来获取文本区域的文本:

$('input#mybutton').click(function() {
    var text = $('textarea#mytextarea').val();
});

当然,这只是猜测,因为您没有提供任何代码:(

更新:

您添加的代码也不正确,因为它在id为description的div中添加了重复的id descriptionID在页面上必须是唯一的

假设你想要一个新的id,这里是你代码的更干净版本:

$.getJSON('/link/' + tenderId, function (data) {
    var $textArea = $("<textarea>", {class: "form-control", id: "descriptionText", rows: "3"}).val(data.description);
    $('#description').empty().append(description);
});

我搞不懂你的方法逻辑;您似乎正在提取一些json数据,然后将其附加到一个文本区域,而在问题描述中,您说您正在尝试保存textarea内容,因此您必须通过POST请求发送它。

此外,<textarea id="description"...>元素是否在您的页面中,或者您将在每次单击按钮时创建它?如果你是这样的情况,你可以尝试以下片段:

$.getJSON('/link/' + tenderId, function (data) { 
  var $description = $("<textarea>");
  $description.attr({
      id:'description',
      class:'form-control',
      rows:'3'})
    .html(data.description);
//you will have then to append this jQuery element, e.g: $("#wrapper").append($description)
});
$('button').click(function(){
var myString = $('#description').val();
})

然后随意使用myString。