简体   繁体   中英

how to get the value of a textarea in jquery?

i have this form and im trying to get the value from the text area. for some reason it doesn't want to.

<form action="/profile/index/sendmessage" method="post" enctype="application/x-www-form-urlencoded">
    <div class="upload_form">
        <dt id="message-label"><label class="optional" for="message">Enter Message</label></dt>
        <dd id="message-element">
        <textarea cols="60" rows="5" id="message" name="message"></textarea></dd>
        <dt id="id-label">&nbsp;</dt>
        <dd id="id-element">
        <input type="hidden" id="id" value="145198" name="id"></dd>
        <dt id="send_message-label">&nbsp;</dt>
        <dd id="send_message-element">
        <input type="submit" class="sendamessage" value="Send" id="send_message" name="send_message"></dd>
    </div>
</form>


$("input.sendamessage").click(function(event) {
    event.preventDefault();

    var message = $('textarea#message').html();
    var id      = $('input#id').val();

    console.log(message + '-' + id);
});

or jsfiddle

any ideas?

textarea 的值也用val方法获取:

var message = $('textarea#message').val();

You need to use .val() for textarea as it is an element and not a wrapper. Try

$('textarea#message').val()

Updated fiddle

你应该使用val()而不是html()

var message = $('#message').val();

在 JavaScript 中:

document.getElementById("message").value

You don't need to use textarea#message

var message = $('textarea#message').val();

You can directly use

var message = $('#message').val();

You should check the textarea is null before you use val() otherwise, you will get undefined error.

if ($('textarea#message') != undefined) {
   var message = $('textarea#message').val();
}

Then, you could do whatever with message.

$('textarea#message') cannot be undefined (if by $ you mean jQuery of course).

$('textarea#message') may be of length 0 and then $('textarea#message').val() would be empty that's all

You can directly use

var message = $.trim($("#message").val());

Read more @ Get the Value of TextArea using the jQuery Val () Method

您还可以通过元素的name 属性获取值。

var message = $("#formId textarea[name=message]").val();

all Values is always taken with .val() .

see the code bellow:

var message = $('#message').val();

You don't need to use .html() . You should go with .val() .

From the doc of .val() :

The .val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined .

var message = $('#message').val();

您还可以通过名称而不是 id 获取值,如下所示:

var message = $('textarea:input[name=message]').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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