Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get textarea text with javascript or Jquery

I have an iframe that contains a textarea, like so:

<html>
<body>

<form id="form1">
<div>
    <textarea id="area1" rows="15"></textarea>
</div>
</form>

</body>
</html>

I want to get the textarea text in the parent page. I've tried this:

var text = $('#frame1').contents().find('#area1').val();

But an empty string is returned. However, if I put a value within <textarea> tags this value is returned successfully:

<textarea id="area1" rows="15">something</textarea>

How can I get the value of the textarea from the page which contains the iframe?

like image 604
antoni Avatar asked Apr 29 '11 11:04

antoni


People also ask

How do I get textarea text?

Use the value property to get the value of a textarea, e.g. const value = textarea. value . The value property can be used to read and set the value of a textarea element. If the textarea is empty, an empty string is returned.

How do I display textarea content in HTML?

Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows. Specifies that on page load the text area should automatically get focus.

Does textarea work like input?

You can't make an input[type=text] work as a <textarea> . Because only HTML form element that's designed to be multiline is textarea.


2 Answers

Reading the <textarea>'s content:

var text1 = document.getElementById('myTextArea').value;     // plain JavaScript
var text2 = $("#myTextArea").val();                          // jQuery

Writing to the <textarea>:

document.getElementById('myTextArea').value = 'new value';   // plain JavaScript
$("#myTextArea").val('new value');                           // jQuery

See demo JSFiddle here.

Do not use .html() or .innerHTML!

jQuery's .html() and JavaScript's .innerHTML should not be used, as they do not pick up changes to the textarea's text.

When the user types in the textarea, the .html() won’t return the typed value, but the original one -- check the demo fiddle above for an example.

like image 65
acdcjunior Avatar answered Oct 12 '22 18:10

acdcjunior


To get the value from a textarea with an id you just have to do

$("#area1").val();

If you are having more than one element with the same id in the document then the HTML is invalid.

like image 20
rahul Avatar answered Oct 12 '22 18:10

rahul