A input field where the user will write what he wants to display
<input type="text" 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 >$(".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?
CodePudding user response:
I think you have a typo here
<div id="paste"> //missing one double quote
CodePudding user response:
There is multiple problems with your code, it should be :
$("#paste").append('<div >' $(this).val() '</div>')
- It should be
$("#input-text").val()not$("#input-text").valueAlso you can change$("#input-text").val()to$(this).val() - You need to wrap your html
<div >$("#input-text").value</div>})also you have a}that should not be there.
Demo
$("#input-text").keyup(function() {
$("#paste").append('<div >' $("#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" placeholder="Input Text">
<div id="paste"></div> //code to be pasted here
CodePudding user response:
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 >');
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 >').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" placeholder="Input Text">
<div id="paste"></div> //code to be pasted here
