问题
I am trying to read the content of a textarea, but .val() does not work for my textarea.
I would be happy, if someone has a solution for me.
Here's my code:
HTML:
<textarea id="details" class="required" rows="5"></textarea>
JS:
$.ajax({
type: "GET",
url: "reserve.php",
data: {
details : $('#details').val(),
...
},
...
});
Thank you!
回答1:
val() works just fine... You must have your error elsewhere.
Example
Probably your selector in not matching. Check for typos and if you applied the correct prefix (# for ID or . for class)
回答2:
This is a valid request, as I have experienced this exact same problem and can report the following:
- No - it's not the selector, one valid object is returned
- No - there is only one element with this id
- No - there is no invalid HTML or bad tag usage as far as I have seen
Yes - there is an answer that isn't a hack or bad code:
$('#myTextArea')[0].value
回答3:
I had the same problem. The solution in my case was, the there was two elements with the id "comment". The jQuery returned the value of the first one, which was empty. If I looked at the source code, I only saw one, since the second was added after an AJAX call. But when is searched in the inspector for "comment" (including the quotes) I saw both elements. I hope this helps you too.
回答4:
Strangely i had a similar issue trying to empty all textareas. It wasnt a selector problem as i was selecting all textareas in the page with $('textarea'). I found that the following worked: $('textarea').text('');
So you could try setting the textarea with: $('textarea').text('my new value');
回答5:
My issue was the I was using a name selector instead of an id selector.
i.e.:
works:
'content': $(this).find('#text_content').val(),
doesn't work:
'content' : $(this).find('input[name=text_content]').val(),
Not sure why the name selector didn't work for the textarea (it worked for all other fields), but there you have it.
回答6:
details : encodeURIComponent($('#details').val())
回答7:
right click on TextAreaFor and select Inspect. Use the id that is generated by your browser, for some reason it generates its own id for TextArea even if you specify it in htmlAttributes. in code: @Html.TextAreaFor(model => model.PendingUserDto.PendingUserNotes, new { htmlAttributes = new { @class = "form-control", id = "pendingUserNotes" } }) in Inspect Window: Test Notes
来源:https://stackoverflow.com/questions/11775547/jquery-val-is-not-working-for-textarea