A input field where the user will write what he wants to display
<input type="text" class="input-text form-control" placeholder="Input Text">
<div id="paste"></div> //code to be pasted here
keyup function called every time user make changes
$("#input-text").keyup(function(){
$("#paste").append(`<div class="form-control">$(".input-text").value</div>`)})
When I write "<tagname Hello /tagname>" in input field, it does not get displayed, rather it gets implemented as an HTML code. How can I correct that?
I think you have a typo here
<div id="paste">
//missing one double quote
There is multiple problems with your code, it should be :
$("#paste").append('<div class="form-control">' + $(this).val() + '</div>')
$("#input-text").val()
not $("#input-text").value
Also you can change $("#input-text").val()
to $(this).val()
<div class="form-control">$("#input-text").value</div>})
also you have a }
that should not be there.Demo
$("#input-text").keyup(function() {
$("#paste").append('<div class="form-control">' + $("#input-text").val() + '</div>')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input-text" class="form-control" placeholder="Input Text">
<div id="paste"></div> //code to be pasted here
All the typo-issues aside, your issue is that you are using .append
with a complete html string.
This will append html.
If you want what you input (eg html tags) to appear as text, then you need to use .text(newtext)
. As you're wrapping the input in a div, the easiest way is to generate the div, then add the text. You could also encode the text when you add it as html, but using .text(txt)
does this for you.
var div = $('<div class="form-control">');
div.text($(this).val())
$("#paste").append(div);
You can make this a single line by using .appendTo()
, which returns the new element rather than .append() which returns the outer element, then chain .text()
.
$("#input-text").keyup(function() {
$('<div class="form-control">').appendTo("#paste").text( $(this).val() );
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input-text" class="form-control" placeholder="Input Text">
<div id="paste"></div> //code to be pasted here