Home > Blockchain >  html() method in jquery need to return textarea with value
html() method in jquery need to return textarea with value

Time:01-30

I'm trying to store the html element of a table which includes textarea tags also. I need to store the textarea with value when I call html() method in jquery.

Code in html:

<div id="test">
    <textarea></textarea>
</div>

After user input for textarea field, for example user inputs "Mango". Then when I call var test = $('#test').html();

it should return the output as "< textarea >Mango< / textarea >"

Any ideas please. Thanks in Advance.

CodePudding user response:

A <textarea> can contain innerHTML, which is displayed when there's no value:

$("#test textarea").append("<strong>Inner</strong> html");
console.log($("textarea").html())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"><textarea></textarea></div>

though it's mostly ignored (as shown above) and lost when user enters a value.

So we can take advantage of that by setting the HTML to the value just before reading the HTML and it should work. Here's a snippet that loops through all text areas as sets their HTML to the value:

// empty on load
console.log($("#test").html())

$("button").click(() => {
    $("textarea").html(function() { return $(this).val(); });
    
    // output the outer #test div's innerHTML 
    // includes both textareas and their newly set HTML
    console.log($("#test").html())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <textarea></textarea>
  <textarea></textarea>
</div>
<button>click me</button>

  • Related