在jQuery中设置textarea的值。

时间:2021-08-19 08:49:54

I am attempting to set a value in a textarea field using jquery with the following code:

我正在尝试使用jquery在textarea字段中设置一个值,代码如下:

$("textarea#ExampleMessage").attr("value", result.exampleMessage);

The issue is, once this code executes, it is not altering the text in the textarea?

问题是,一旦这段代码执行,它不会改变文本区域中的文本吗?

However when performing an alert($("textarea#ExampleMessage").attr("value")) the newly set value is returned?

但是,当执行警报($(“textarea#ExampleMessage”).attr(“value”))时,新设置的值会返回吗?

23 个解决方案

#1


769  

Have you tried val?

你有试过瓦尔?

$("textarea#ExampleMessage").val(result.exampleMessage);

#2


68  

Textarea has no value attribute, its value comes between tags, i.e: <textarea>my text</textarea>, it is not like the input field (<input value="my text" />). That's why attr doesn't work :)

Textarea没有value属性,它的值在标签i之间。e: ,不像输入字段()。这就是为什么attr不起作用:)

#3


43  

$("textarea#ExampleMessage").val() in jquery just a magic.

$(“textarea#ExampleMessage”).val()在jquery中很神奇。

You should notice that textarea tag using inner html to display and not in value attribute just like input tag.

您应该注意到,textarea标签使用内部html来显示,而不是像输入标签那样使用value属性。

<textarea>blah blah</textarea>
<input type="text" value="blah blah"/>

You should use

你应该使用

$("textarea#ExampleMessage").html(result.exampleMessage)

or

$("textarea#ExampleMessage").text(result.exampleMessage)

depend on if you want to display it as html tags or plain text.

取决于您是否希望将其显示为html标记或纯文本。

#4


13  

I think this should work :

我认为这应该行得通:

$("textarea#ExampleMessage").val(result.exampleMessage);

#5


13  

Oohh come on boys! it works just with

Oohh来吧男孩!它的工作原理与

$('#your_textarea_id').val('some_value');

#6


10  

i had the same question so i decided to try it in the current browsers (we're one and a half year later in time after this question), and this (.val) works

我有同样的问题,所以我决定在当前的浏览器中尝试(我们在这个问题之后的一年半之后),这个(.val)工作。

$("textarea#ExampleMessage").val(result.exampleMessage); 

for

  • IE8
  • IE8
  • FF 3.6
  • FF 3.6
  • FF4
  • FF4
  • Opera 11
  • Opera 11
  • Chrome 10
  • Chrome 10

#7


8  

I had same issue and this solution didn't work but what worked was to use html

我也遇到了同样的问题,这个解决方案不管用,但起作用的是使用html

$('#your_textarea_id').html('some_value');

#8


5  

There the problem : I need to generate html code from the contain of a given div. Then, I have to put this raw html code in a textarea. When I use the function $(textarea).val() like this :

这里的问题是:我需要从一个给定的div中生成html代码。然后,我必须将这个原始的html代码放在一个textarea中。当我像这样使用函数$(textarea).val()时:

$(textarea).val("some html like < input type='text' value='' style="background: url('http://www.w.com/bg.gif') repeat-x center;" /> bla bla");

美元(文本区域)。val(“一些html如< input type='text' value= " style="background: url('http://www.w.com/bg.gif') repeat-x center;”/ > bla bla”);

or

$('#idTxtArGenHtml').val( $('idDivMain').html() );

$(" # idTxtArGenHtml”)。瓦尔($(' idDivMain '). html());

I had problem with some special character ( & ' " ) when they are between quot. But when I use the function : $(textarea).html() the text is ok.

我对某些特殊的人物(和“)”有问题。但是当我使用函数:$(textarea).html()时,文本没有问题。

There an example form :

有一个例子形式:

<FORM id="idFormContact" name="nFormContact" action="send.php" method="post"  >
    <FIELDSET id="idFieldContact" class="CMainFieldset">
        <LEGEND>Test your newsletter&raquo; </LEGEND> 
        <p>Send to &agrave; : <input id='idInpMailList' type='text' value='youremail@gmail.com' /></p>
        <FIELDSET  class="CChildFieldset">
            <LEGEND>Subject</LEGEND>
            <LABEL for="idNomClient" class="CInfoLabel">Enter the subject: *&nbsp</LABEL><BR/>
          <INPUT value="" name="nSubject" type="text" id="idSubject" class="CFormInput" alt="Enter the Subject" ><BR/>
    </FIELDSET>
    <FIELDSET  class="CChildFieldset">
        <INPUT id="idBtnGen" type="button" value="Generate" onclick="onGenHtml();"/>&nbsp;&nbsp;
          <INPUT id="idBtnSend" type="button" value="Send" onclick="onSend();"/><BR/><BR/>
            <LEGEND>Message</LEGEND>
                <LABEL for="idTxtArGenHtml" class="CInfoLabel">Html code : *&nbsp</LABEL><BR/>
                <span><TEXTAREA  name="nTxtArGenHtml" id="idTxtArGenHtml" width='100%' cols="69" rows="300" alt="enter your message" ></TEXTAREA></span>
        </FIELDSET>
    </FIELDSET>
</FORM>

And javascript/jquery code that don't work to fill the textarea is :

而javascript/jquery代码无法填充文本区域的是:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html()  );
}

Finaly the solution :

最终解决方案:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html() );
  $('#idTxtArGenHtml').parent().replaceWith( '<span>'+$('#idTxtArGenHtml').parent().html()+'</span>');
}

The trick is wrap your textarea with a span tag to help with the replaceWith function. I'm not sure if it's very clean, but it's work perfect too add raw html code in a textarea.

诀窍是使用span标记将textarea包装起来,以帮助实现replaceWith函数。我不确定它是否很干净,但是它的工作非常完美,在一个文本区域中添加了原始的html代码。

#9


4  

Text Area doesnot have value. jQuery .html() works in this case

文本区域没有值。在这种情况下,jQuery .html()工作。

$("textarea#ExampleMessage").html(result.exampleMessage);

#10


3  

textarea doesn't store values as

不将值存储为文本区域

<textarea value="someString">

instead, it stores values in this format:

相反,它以这种格式存储值:

<textarea>someString</textarea>

So attr("value","someString") gets you this result:

所以attr("value","someString")会得到这样的结果:

<textarea value="someString">someOLDString</textarea>.

try $("#textareaid").val() or $("#textareaid").innerHTML instead.

试着$(" # textareaid ").val()或$(" # textareaid ")。innerHTML。

#11


3  

On android .val and .html didn't work. $('#id').text("some value") did the job.

在android .val和。html上不能运行。$(" # id”)。文本(“一些值”)完成了这项工作。

#12


2  

I tried with .val() .text() .html() and had some bugs using jQuery to read or set value of a textarea... i endup using native js

我试着与.val()。text()使用jQuery . html()和有一些错误读取或设置值的文本区域……虽然我使用本机js

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});

#13


2  

It works for me.... I have built a face book wall...

这对我来说是....我建了一面脸书墙……

Here is the basis of my code:

以下是我的代码的基础:

// SETS MY TEXT AREA TO EMPTY (NO VALUE)
$('textarea#message_wall').val('');

#14


2  

We can either use .val() or .text() methods to set values. we need to put value inside val() like val("hello").

我们可以使用.val()或.text()方法来设置值。我们需要在val()中设置值,比如val(“hello”)。

  $(document).ready(function () {
    $("#submitbtn").click(function () {
      var inputVal = $("#inputText").val();
      $("#txtMessage").val(inputVal);
    });
  });

Check example here: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

检查的例子:http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

#15


2  

To set textarea value of encoded HTML (to show as HTML) you should use .html( the_var ) but as mentioned if you try and set it again it may (and probably) will not work.

要设置编码的HTML的textarea值(以HTML的形式显示),您应该使用. HTML (the_var),但如前所述,如果您尝试再次设置它,它可能(而且可能)不会工作。

You can fix this by emptying the textarea .empty() and then setting it again with .html( the_var )

您可以通过清空textarea .empty(),然后使用.html(the_var)再次设置它来解决这个问题

Here's a working JSFiddle: https://jsfiddle.net/w7b1thgw/2/

这是一个工作JSFiddle:https://jsfiddle.net/w7b1thgw/2/

jQuery(function($){
    
    $('.load_html').click(function(){
        var my_var = $(this).data('my_html');
        $('#dynamic_html').html( my_var ); 
    });
    
    $('#clear_html').click(function(){
        $('#dynamic_html').empty(); 
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="dynamic_html"></textarea>
<a id="google_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;google.com&quot;&gt;google.com&lt;/a&gt;">Google HTML</a>
<a id="yahoo_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;yahoo.com&quot;&gt;yahoo.com&lt;/a&gt;">Yahoo HTML</a>
<a id="clear_html" href="#">Clear HTML</a>

#16


1  

The accepted answer works for me, but only after I realized I had to execute my code after the page was finished loading. In this situation inline script didn't work, I guess because #my_form wasn't done loading yet.

被接受的答案对我有效,但直到我意识到我必须在页面完成加载后执行我的代码。在这种情况下,内联脚本不起作用,因为#my_form还没有完成加载。

$(document).ready(function() {
  $("#my_form textarea").val('');
});

#17


1  

You can even use the below snippet.

您甚至可以使用下面的代码片段。

$("textarea#ExampleMessage").append(result.exampleMessage);

#18


1  

When I had JQuery v1.4.4 in the page, neither of these worked. When injecting JQuery v1.7.1 into my page, it worked finally. So in my case, it was my JQuery version that was causing the issue.

当我在页面中有JQuery v1.4.4时,这两种方法都不起作用。当将JQuery v1.7.1注入我的页面时,它最终成功了。在我的例子中,是我的JQuery版本引起了这个问题。

id ==> textareaid

id = = > textareaid

======================

= = = = = = = = = = = = = = = = = = = = = =

var script1 = document.createElement("script");
script1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
document.body.appendChild(script1);

var script2 = document.createElement("script"); 
script2.type = "text/javascript"; 
script2.innerHTML = "var $jq171 = $.noConflict();"; 
document.body.appendChild(script2);

$jq171('#textareaid').val('xxx');

#19


1  

Just use textarea Id by its type like it:

只需按其类型使用textarea Id:

$("textarea#samplID").val()

#20


0  

Just use this code and you will always have the value:

只要使用这段代码,你就会永远拥有:

var t = $(this); var v = t.val() || t.html() || t.text();

t = $ var(这个);var v = t.val() || t.html() || t.text();

So it will check val() and set its value. If val() gets an empty string, NULL, NaN o.s. it will check for html() and then for text()...

它将检查val()并设置它的值。如果val()得到一个空字符串,NULL, NaN o.s.,它将检查html()和text()…

#21


0  

This works:

如此:

var t = $('#taCommentSalesAdministration');
t.val('Hi');

Remember, the tricky part here is making sure you use the correct ID. And before you use the ID make sure you put # before it.

记住,这里的棘手的部分是之前确保您使用正确的ID,您使用ID之前确保你把#。

#22


0  

Using $("textarea#ExampleMessage").html('whatever you want to put here'); can be a good way, because .val() can have problems when you are using data from database.

使用$(" # ExampleMessage文本区域”)。html('whatever you want to put here');这是一种很好的方法,因为.val()在使用来自数据库的数据时可能会出现问题。

For example:

例如:

A database field named as description has the following value asjkdfklasdjf sjklñadf. In this case using .val() to assign value to textarea can be a tedious job.

一个名为description的数据库字段具有以下值asjkdfkdfklasdjf sjklnadf。在这种情况下,使用.val()为textarea赋值可能是一项繁琐的工作。

#23


0  

I think there is missing one important aspect:

我认为这里漏掉了一个重要的方面:

$('#some-text-area').val('test');

works only when there is an ID selector (#)

只有在有ID选择器(#)时才有效

for class selector there is an option to use native value like:

对于类选择器,有一个使用本地值的选项:

$('.some-text-area')[0].value = 'test';

#1


769  

Have you tried val?

你有试过瓦尔?

$("textarea#ExampleMessage").val(result.exampleMessage);

#2


68  

Textarea has no value attribute, its value comes between tags, i.e: <textarea>my text</textarea>, it is not like the input field (<input value="my text" />). That's why attr doesn't work :)

Textarea没有value属性,它的值在标签i之间。e: ,不像输入字段()。这就是为什么attr不起作用:)

#3


43  

$("textarea#ExampleMessage").val() in jquery just a magic.

$(“textarea#ExampleMessage”).val()在jquery中很神奇。

You should notice that textarea tag using inner html to display and not in value attribute just like input tag.

您应该注意到,textarea标签使用内部html来显示,而不是像输入标签那样使用value属性。

<textarea>blah blah</textarea>
<input type="text" value="blah blah"/>

You should use

你应该使用

$("textarea#ExampleMessage").html(result.exampleMessage)

or

$("textarea#ExampleMessage").text(result.exampleMessage)

depend on if you want to display it as html tags or plain text.

取决于您是否希望将其显示为html标记或纯文本。

#4


13  

I think this should work :

我认为这应该行得通:

$("textarea#ExampleMessage").val(result.exampleMessage);

#5


13  

Oohh come on boys! it works just with

Oohh来吧男孩!它的工作原理与

$('#your_textarea_id').val('some_value');

#6


10  

i had the same question so i decided to try it in the current browsers (we're one and a half year later in time after this question), and this (.val) works

我有同样的问题,所以我决定在当前的浏览器中尝试(我们在这个问题之后的一年半之后),这个(.val)工作。

$("textarea#ExampleMessage").val(result.exampleMessage); 

for

  • IE8
  • IE8
  • FF 3.6
  • FF 3.6
  • FF4
  • FF4
  • Opera 11
  • Opera 11
  • Chrome 10
  • Chrome 10

#7


8  

I had same issue and this solution didn't work but what worked was to use html

我也遇到了同样的问题,这个解决方案不管用,但起作用的是使用html

$('#your_textarea_id').html('some_value');

#8


5  

There the problem : I need to generate html code from the contain of a given div. Then, I have to put this raw html code in a textarea. When I use the function $(textarea).val() like this :

这里的问题是:我需要从一个给定的div中生成html代码。然后,我必须将这个原始的html代码放在一个textarea中。当我像这样使用函数$(textarea).val()时:

$(textarea).val("some html like < input type='text' value='' style="background: url('http://www.w.com/bg.gif') repeat-x center;" /> bla bla");

美元(文本区域)。val(“一些html如< input type='text' value= " style="background: url('http://www.w.com/bg.gif') repeat-x center;”/ > bla bla”);

or

$('#idTxtArGenHtml').val( $('idDivMain').html() );

$(" # idTxtArGenHtml”)。瓦尔($(' idDivMain '). html());

I had problem with some special character ( & ' " ) when they are between quot. But when I use the function : $(textarea).html() the text is ok.

我对某些特殊的人物(和“)”有问题。但是当我使用函数:$(textarea).html()时,文本没有问题。

There an example form :

有一个例子形式:

<FORM id="idFormContact" name="nFormContact" action="send.php" method="post"  >
    <FIELDSET id="idFieldContact" class="CMainFieldset">
        <LEGEND>Test your newsletter&raquo; </LEGEND> 
        <p>Send to &agrave; : <input id='idInpMailList' type='text' value='youremail@gmail.com' /></p>
        <FIELDSET  class="CChildFieldset">
            <LEGEND>Subject</LEGEND>
            <LABEL for="idNomClient" class="CInfoLabel">Enter the subject: *&nbsp</LABEL><BR/>
          <INPUT value="" name="nSubject" type="text" id="idSubject" class="CFormInput" alt="Enter the Subject" ><BR/>
    </FIELDSET>
    <FIELDSET  class="CChildFieldset">
        <INPUT id="idBtnGen" type="button" value="Generate" onclick="onGenHtml();"/>&nbsp;&nbsp;
          <INPUT id="idBtnSend" type="button" value="Send" onclick="onSend();"/><BR/><BR/>
            <LEGEND>Message</LEGEND>
                <LABEL for="idTxtArGenHtml" class="CInfoLabel">Html code : *&nbsp</LABEL><BR/>
                <span><TEXTAREA  name="nTxtArGenHtml" id="idTxtArGenHtml" width='100%' cols="69" rows="300" alt="enter your message" ></TEXTAREA></span>
        </FIELDSET>
    </FIELDSET>
</FORM>

And javascript/jquery code that don't work to fill the textarea is :

而javascript/jquery代码无法填充文本区域的是:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html()  );
}

Finaly the solution :

最终解决方案:

function onGenHtml(){
  $('#idTxtArGenHtml').html( $("#idDivMain").html() );
  $('#idTxtArGenHtml').parent().replaceWith( '<span>'+$('#idTxtArGenHtml').parent().html()+'</span>');
}

The trick is wrap your textarea with a span tag to help with the replaceWith function. I'm not sure if it's very clean, but it's work perfect too add raw html code in a textarea.

诀窍是使用span标记将textarea包装起来,以帮助实现replaceWith函数。我不确定它是否很干净,但是它的工作非常完美,在一个文本区域中添加了原始的html代码。

#9


4  

Text Area doesnot have value. jQuery .html() works in this case

文本区域没有值。在这种情况下,jQuery .html()工作。

$("textarea#ExampleMessage").html(result.exampleMessage);

#10


3  

textarea doesn't store values as

不将值存储为文本区域

<textarea value="someString">

instead, it stores values in this format:

相反,它以这种格式存储值:

<textarea>someString</textarea>

So attr("value","someString") gets you this result:

所以attr("value","someString")会得到这样的结果:

<textarea value="someString">someOLDString</textarea>.

try $("#textareaid").val() or $("#textareaid").innerHTML instead.

试着$(" # textareaid ").val()或$(" # textareaid ")。innerHTML。

#11


3  

On android .val and .html didn't work. $('#id').text("some value") did the job.

在android .val和。html上不能运行。$(" # id”)。文本(“一些值”)完成了这项工作。

#12


2  

I tried with .val() .text() .html() and had some bugs using jQuery to read or set value of a textarea... i endup using native js

我试着与.val()。text()使用jQuery . html()和有一些错误读取或设置值的文本区域……虽然我使用本机js

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});

#13


2  

It works for me.... I have built a face book wall...

这对我来说是....我建了一面脸书墙……

Here is the basis of my code:

以下是我的代码的基础:

// SETS MY TEXT AREA TO EMPTY (NO VALUE)
$('textarea#message_wall').val('');

#14


2  

We can either use .val() or .text() methods to set values. we need to put value inside val() like val("hello").

我们可以使用.val()或.text()方法来设置值。我们需要在val()中设置值,比如val(“hello”)。

  $(document).ready(function () {
    $("#submitbtn").click(function () {
      var inputVal = $("#inputText").val();
      $("#txtMessage").val(inputVal);
    });
  });

Check example here: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

检查的例子:http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

#15


2  

To set textarea value of encoded HTML (to show as HTML) you should use .html( the_var ) but as mentioned if you try and set it again it may (and probably) will not work.

要设置编码的HTML的textarea值(以HTML的形式显示),您应该使用. HTML (the_var),但如前所述,如果您尝试再次设置它,它可能(而且可能)不会工作。

You can fix this by emptying the textarea .empty() and then setting it again with .html( the_var )

您可以通过清空textarea .empty(),然后使用.html(the_var)再次设置它来解决这个问题

Here's a working JSFiddle: https://jsfiddle.net/w7b1thgw/2/

这是一个工作JSFiddle:https://jsfiddle.net/w7b1thgw/2/

jQuery(function($){
    
    $('.load_html').click(function(){
        var my_var = $(this).data('my_html');
        $('#dynamic_html').html( my_var ); 
    });
    
    $('#clear_html').click(function(){
        $('#dynamic_html').empty(); 
    });
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="dynamic_html"></textarea>
<a id="google_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;google.com&quot;&gt;google.com&lt;/a&gt;">Google HTML</a>
<a id="yahoo_html" class="load_html" href="#" data-my_html="&lt;a href=&quot;yahoo.com&quot;&gt;yahoo.com&lt;/a&gt;">Yahoo HTML</a>
<a id="clear_html" href="#">Clear HTML</a>

#16


1  

The accepted answer works for me, but only after I realized I had to execute my code after the page was finished loading. In this situation inline script didn't work, I guess because #my_form wasn't done loading yet.

被接受的答案对我有效,但直到我意识到我必须在页面完成加载后执行我的代码。在这种情况下,内联脚本不起作用,因为#my_form还没有完成加载。

$(document).ready(function() {
  $("#my_form textarea").val('');
});

#17


1  

You can even use the below snippet.

您甚至可以使用下面的代码片段。

$("textarea#ExampleMessage").append(result.exampleMessage);

#18


1  

When I had JQuery v1.4.4 in the page, neither of these worked. When injecting JQuery v1.7.1 into my page, it worked finally. So in my case, it was my JQuery version that was causing the issue.

当我在页面中有JQuery v1.4.4时,这两种方法都不起作用。当将JQuery v1.7.1注入我的页面时,它最终成功了。在我的例子中,是我的JQuery版本引起了这个问题。

id ==> textareaid

id = = > textareaid

======================

= = = = = = = = = = = = = = = = = = = = = =

var script1 = document.createElement("script");
script1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
document.body.appendChild(script1);

var script2 = document.createElement("script"); 
script2.type = "text/javascript"; 
script2.innerHTML = "var $jq171 = $.noConflict();"; 
document.body.appendChild(script2);

$jq171('#textareaid').val('xxx');

#19


1  

Just use textarea Id by its type like it:

只需按其类型使用textarea Id:

$("textarea#samplID").val()

#20


0  

Just use this code and you will always have the value:

只要使用这段代码,你就会永远拥有:

var t = $(this); var v = t.val() || t.html() || t.text();

t = $ var(这个);var v = t.val() || t.html() || t.text();

So it will check val() and set its value. If val() gets an empty string, NULL, NaN o.s. it will check for html() and then for text()...

它将检查val()并设置它的值。如果val()得到一个空字符串,NULL, NaN o.s.,它将检查html()和text()…

#21


0  

This works:

如此:

var t = $('#taCommentSalesAdministration');
t.val('Hi');

Remember, the tricky part here is making sure you use the correct ID. And before you use the ID make sure you put # before it.

记住,这里的棘手的部分是之前确保您使用正确的ID,您使用ID之前确保你把#。

#22


0  

Using $("textarea#ExampleMessage").html('whatever you want to put here'); can be a good way, because .val() can have problems when you are using data from database.

使用$(" # ExampleMessage文本区域”)。html('whatever you want to put here');这是一种很好的方法,因为.val()在使用来自数据库的数据时可能会出现问题。

For example:

例如:

A database field named as description has the following value asjkdfklasdjf sjklñadf. In this case using .val() to assign value to textarea can be a tedious job.

一个名为description的数据库字段具有以下值asjkdfkdfklasdjf sjklnadf。在这种情况下,使用.val()为textarea赋值可能是一项繁琐的工作。

#23


0  

I think there is missing one important aspect:

我认为这里漏掉了一个重要的方面:

$('#some-text-area').val('test');

works only when there is an ID selector (#)

只有在有ID选择器(#)时才有效

for class selector there is an option to use native value like:

对于类选择器,有一个使用本地值的选项:

$('.some-text-area')[0].value = 'test';