Ustaw wartość textarea w jQuery

Próbuję ustawić wartość w polu textarea używając jquery z następującym kodem:

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

Problem polega na tym, że po wykonaniu tego kodu nie zmienia on tekstu w textarea?

Jednak podczas wykonywania alert($("textarea#ExampleMessage").attr("value")) zwracana jest nowo ustawiona wartość?

Author: Ryan Wheale, 2009-01-06

23 answers

Próbowałaś Val?

$("textarea#ExampleMessage").val(result.exampleMessage);
 788
Author: enobrev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-06 06:10:17

Textarea nie ma atrybutu value, jego wartość pojawia się pomiędzy znacznikami, np.: <textarea>my text</textarea>, nie jest tak jak Pole input (<input value="my text" />). Dlatego attr nie działa:)

 68
Author: danivalentin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-09-16 22:20:36

$("textarea#ExampleMessage").val() w jquery po prostu magia.

Powinieneś zauważyć, że textareaTag używając wewnętrznego htmldo wyświetlenia i nie w atrybucie value tak jak input tag.

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

Należy użyć

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

Lub

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

Zależy od tego, czy chcesz wyświetlić go jako znaczniki html lub zwykły tekst.

 44
Author: CallMeLaNN,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-07 11:52:33

Myślę, że to powinno zadziałać:

$("textarea#ExampleMessage").val(result.exampleMessage);
 13
Author: Jomit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-06 06:19:29

No dalej chłopcy! działa tylko z

$('#your_textarea_id').val('some_value');
 13
Author: Mik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-18 12:14:27

Miałem to samo pytanie, więc postanowiłem spróbować w obecnych przeglądarkach (mamy półtora roku później po tym pytaniu), i to (.val) działa

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

Dla

  • IE8
  • FF 3.6
  • FF4
  • Opera 11
  • Chrome 10
 10
Author: Michel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-06 07:53:19

Miałem ten sam problem i to rozwiązanie nie działało, ale zadziałało użycie html

$('#your_textarea_id').html('some_value');
 8
Author: dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-18 12:13:36

Na Androidzie .val i .html nie zadziałały.

$('#id').text("some value")
Wykonałem robotę.
 7
Author: Dan Ochiana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-02 10:04:38

Jest problem : muszę wygenerować kod html z zawartości danego div. Następnie muszę umieścić ten surowy kod html w textarea. Kiedy używam funkcji $(textarea).val () tak:

$(textarea).val ("jakiś html jak bla bla");

Lub

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

Miałem problem z niektórymi znak specjalny ( & '" ), gdy znajdują się pomiędzy quot. Ale kiedy używam funkcji : $(textarea).html () tekst jest ok.

Tam przykładowa forma:

<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='[email protected]' /></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>

A kod javascript / jquery, który nie działa do wypełnienia textarea to:

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

Ostatecznie rozwiązanie:

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

Sztuką jest owinięcie textarea znacznikiem span, aby pomóc w funkcji replaceWith. Nie jestem pewien, czy jest to bardzo czyste, ale to praca idealna zbyt dodać surowy kod html w textarea.

 5
Author: Mathieua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-02 18:09:22

Obszar tekstowy nie ma wartości. jQuery .html () działa w tym przypadku

$("textarea#ExampleMessage").html(result.exampleMessage);
 4
Author: user2989278,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-04 07:59:25

Textarea nie przechowuje wartości jako

<textarea value="someString">

Zamiast tego przechowuje wartości w tym formacie:

<textarea>someString</textarea>

Więc attr("value","someString") daje Ci ten wynik:

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

Zamiast tego spróbuj $("#textareaid").val() lub $("#textareaid").innerHTML.

 3
Author: Luka Ramishvili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-19 14:49:15

Próbowałem z .val() .text() .html() i miał kilka błędów za pomocą jQuery odczytać lub ustawić wartość textarea... używam natywnego js

$('#message').blur(function() {    
    if (this.value == '') { this.value = msg_greeting; }
});
 2
Author: Antony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-09 12:59:53

U mnie działa.... Zbudowałem ścianę z książkami twarzy...

Oto podstawa mojego kodu:

// SETS MY TEXT AREA TO EMPTY (NO VALUE)
$('textarea#message_wall').val('');
 2
Author: Edgar Villegas Alvarado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-24 20:05:18

Możemy użyć.val () lub .metody text () do ustawiania wartości. musimy umieścić wartość wewnątrz Val () jak val ("hello").

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

Sprawdź przykład tutaj: http://www.codegateway.com/2012/03/set-value-to-textarea-jquery.html

 2
Author: Avinash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-28 15:29:34

Aby ustawić wartość textarea zakodowanego HTML (aby pokazać jako HTML) należy użyć .html( the_var ), ale jak wspomniano, jeśli spróbujesz ustawić ją ponownie, może to (i prawdopodobnie) nie zadziałać.

Można to naprawić, opróżniając textarea .empty(), a następnie ustawiając go ponownie za pomocą .html( the_var )

Oto działa 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>
 2
Author: sMyles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-02 20:19:54

Zaakceptowana odpowiedź działa na mnie, ale dopiero po tym, jak zdałem sobie sprawę, że muszę wykonać mój kod po zakończeniu ładowania strony. W tej sytuacji skrypt inline nie dziaĹ 'a, chyba dlatego, Ĺźe #my_form nie zostaĹ' jeszcze wczytywany.

$(document).ready(function() {
  $("#my_form textarea").val('');
});
 1
Author: pdub23,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-19 04:54:06

Możesz nawet użyć poniższego fragmentu.

$("textarea#ExampleMessage").append(result.exampleMessage);
 1
Author: shyamshyre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-19 14:48:14

Kiedy miałem JQuery v1. 4. 4 na stronie, żadne z nich nie działało. Podczas wstrzykiwania JQuery v1. 7. 1 na moją stronę, zadziałało w końcu. Więc w moim przypadku, to moja wersja JQuery była przyczyną problemu.

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');
 1
Author: MacGyver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-12 21:09:50

Po prostu użyj textarea Id według jego Typu, Jak to:

$("textarea#samplID").val()
 1
Author: S.Mohamed Mahdi Ahmadian zadeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-09 08:47:55

Po prostu użyj tego kodu, a zawsze będziesz miał wartość:

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

Więc sprawdzi Val () i ustawi jej wartość. Jeśli val() otrzyma pusty łańcuch znaków, NULL, NaN o. s. sprawdzi, czy nie ma html (), a następnie text ()...

 0
Author: Simon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-15 11:57:04

To działa:

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

Pamiętaj, że najtrudniejszą częścią jest upewnienie się, że używasz poprawnego identyfikatora. I zanim użyjesz identyfikatora upewnij się, że umieściłeś # przed nim.

 0
Author: ADL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-22 18:33:23

Używanie $("textarea#ExampleMessage").html('whatever you want to put here'); może być dobrym sposobem, ponieważ .val() może mieć problemy, gdy używasz danych z bazy danych.

Na przykład:

Pole bazy danych o nazwie description ma następującą wartość asjkdfklasdjf sjklñadf. W tym przypadku za pomocą .Val() przypisanie wartości do textarea może być żmudnym zadaniem.

 0
Author: user306265,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-01 15:47:02

Myślę, że brakuje jednego ważnego aspektu:

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

Działa tylko wtedy, gdy istnieje selektor ID (#)

Dla selektora klas istnieje możliwość użycia natywnej wartości, takiej jak:

$('.some-text-area')[0].value = 'test';
 0
Author: user2846569,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-14 11:57:31