0

My code:

var element = '<button>'+text+'</button>';
$('#output').append(element+"\n");

HTML

<textarea id="output" readonly></textarea>

I want it so the element (button) display in textarea as text not element. I want it to display:

'<button>Hi</button>'

if text = "Hi"
Any ideas ?

killereks
  • 189
  • 1
  • 12
  • Possible duplicate: http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript – Jared Sep 30 '16 at 15:45

2 Answers2

0

Use .val() instead of .append():

$('#output').val(element+"\n");
j08691
  • 204,283
  • 31
  • 260
  • 272
0

As mentioned in the other answer, use val() but you want to get the existing value before overwriting it. The reason for this answer being posted is due to the other one not being updated.

Working Demo

$("#Example").on( "click", function() {
  //Add new input before existing content
$('#output').val($('#input').val()+"\n"+$('#output').val());
  //Add new input after existing content
//$('#output').val( $('#output').val() +$('#input').val()+ "\n");  
 $('#input').val('');
  $('#input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="input"/><button id="Example">Add</button><br/>
<textarea id="output" readonly></textarea>

JS Fiddle Demo

To preset the text into a button you can wrap the button tags around the input value.

Example: "<button>"+$('#input').val()+"</button>" JS Fiddle Demo 2

Demo Two

$("#Example").on( "click", function() {
//New input before existing content
 $('#output').val("<button>"+$('#input').val()+"</button>\n"+$('#output').val());
 //New input after existing content
 //$('#output').val( $('#output').val() +"<button>"+$('#input').val()+ "</button>\n");
  $('#input').val('');
  $('#input').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="input"/><button id="Example">Add</button><br/>
<textarea id="output" readonly></textarea>

If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.

I hope this help. Happy coding!

NewToJS
  • 2,762
  • 3
  • 14
  • 22