xxx xxx - 6 months ago 7
HTML Question

How can I make HTML code non-execute?

What I want to do is allow the user to input a string then display that string in the web page inside a

div
element, but I don't want the user to be able to add a bold tag or anything that would actually make the HTML text bold. How could I make it so the text entered by the user does not get converted into HTML code, if the text has an HTML tag in it?

Answer

use .text() when setting the text in the div rather than .HTML. This will render it as text instead of html.

$(document).ready(function() {
  // Handler for .ready() called.

  $("#change-it").click(function() {
    var userLink = $('#usr-input').val().replace(/.*?:\/\//g, "");
    $('#users-text').text(userLink);
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" class="form-control" id="usr-input">
<br>
<button id="change-it" type="button">Update Text</button> 
<br>
<div id="users-text"></div>