简体   繁体   中英

insert text into <textarea>

I'm trying to insert some text in a file into <textarea></textarea> in an html file when one clicks a link in a different html page.

html1.html:

<a href="#" id="link">click to add text</a>

html2.html:

<form action="...">
   <textarea id="txt"></textarea>
</form> 

js:

$(".link").click(function(){
   window.location = "./html2.html";
   var text = $("#some_id").text();
   $("#txt").val(text)
});

Once you migrate to the new page any further JS execution is lost. You'd have to do something like this, passing the text to the new page in a query string variable:

$(".link").click(function(){
   var encodedText = encodeURIComponent($("#some_id").text());
   window.location = "./html2.html?txt=" + encodedText;
});

And have some code like this on your html2.html page:

var capturedText = window.location.search.match(/(\?|&)txt=(.*?)(&|$)/);
capturedText = capturedText ? decodeURIComponent(capturedText[2]) : '';
$("#txt").val(capturedText);

If some_id is in html2.html , then it's easy: Have the JavaScript in html2.html fill in the text

$("#txt").val($("#some_id").text());

If some_id is in html1.html , you should send the value to the server and fill in the textarea on the server-side. In the event that this is unnecessarily complicated or unfeasible, you can pass the text in a number of different ways, the most common being:

  • in the URL html2.html?text="my text"
  • in a cookie (not recommended in most cases)

If you do it via URL, simply extract the text from the URL in the JavaScript on html2.html .

Once you run "window.location", the new page will start loading, and the script will stop executing.

Additionally, you can't modify elements on the future page.

Your best shot is loading html2.html#someTextHere , and on html2.html copy the text from the hash into the textarea.

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