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?
Use createTextNode(value) and append it to your element(Standard solution) or innerText(Non standard solution) instead of innerHTML.
For a JQuery solution look at Dan Weber's answer.
here's a neat little function to sanitize untrusted text:
function sanitize(ht){ // tested in ff, ch, ie9+
return new Option(ht).innerHTML;
}
example input/output:
sanitize(" Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World");
// == " Hello <img src=data:image/png, onmouseover=alert(666) onerror=alert(666)> World"
It will achieve the same results as setting elm.textContent=str;, but as a function, you can use it easier inline, like to run markdown after you sanitize() so that you can pretty-format input (eg. linking URLs) without running arbitrary HTML from the user.
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>
Why not simply use .text() ?
$('#in').on('keyup', function(e) {
$('#out').text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="in">
<br>
<div id="out"></div>
Related
I have written the code but the jquery code isn't getting executed.
Enter URL :<input type="text">
<button id="btn"> continue
</button>
<div contenteditable="true"
id="bod">
Click on this text to start writting</div>
$(document).ready(function(){
$("btn").click(function(){
$("bod").append($('input').html('<img alt="" src="'+$(this).val()+'">'))
})
});
Also I wanna use "input" or "textarea" instead of since I wanna tag that field with ng-model(angularjs).
I believe this is what you're trying to accomplish:
For one, you are trying to reference your elements with an id selector without #.
$("bod") should be $("#bod"), etc. '#" indicates an ID.
And also the way you were retrieving the value for input was all wrong.
Also if you want the value of one item, use an ID. Otherwise you'll get an array just using a generic element selector. I gave your input an id, so you weren't just trying to get a value off of $('input')
(I put a placeholder image address in your value, you can remove that)
Also view the snippet full screen. The small view makes it look like your text is being removed, but it's not really. It's just that when the img is appended, the baseline for everything is lower than the window in the snippet viewer.
$(document).ready(function(){
$("#btn").click(function(){
$("#bod").append('<img alt="" src="'+$('#inp').val()+'">');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter URL :<input id="inp" type="text" value="http://placehold.it/300">
<button id="btn">continue</button>
<div contenteditable="true" id="bod">Click on this text to start writting</div>
If i have understood your requirement correctly then JQuery code should be like this:
$(document).ready(function(){
$("#btn").click(function(){
var bodElem = $("#bod");
var url = $("input").val();
$('<img alt="" src="'+ url +'">').insertAfter(bodElem);
});
});
I have text boxes in a form where users can input formatted text or raw HTML. It all works fine, however is a user doesn't close a tag (like a bold tag), then it ruins all HTML formatting after it (it all becomes bold).
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
You may try jquery-clean
$.htmlClean($myContent);
Is there a way to either validate the user's input, automatically close tags, or somehow wrap the user input in an element to stop it leaking over?
Yes: When the user is done editing the text area, you can parse what they've written using the browser, then get an HTML version of the parsed result from the browser:
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
Live example — type an unclosed tag in and click the button:
$("input[type=button]").on("click", function() {
var div = $("<div>");
div.html($("#the-textarea").val());
var html = div.html();
$(document.body).append("<p>You wrote:</p><hr>" + html + "<hr>End of what you wrote.");
});
<p>Type something unclosed here:</p>
<textarea id="the-textarea" rows="5" cols="40"></textarea>
<br><input type="button" value="Click when ready">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Important Note: If you're going to store what they write and then display it to anyone else, there is no client-side solution, including the above, which is safe. Instead, you must use a server-side solution to "sanitize" the HTML you get from them, to remove (for instance) malicious content, etc. All the above does is help you get mostly-well-formed markup, not safe markup.
Even if you're just displaying it to them, it would still be best to sanitize it, since they can work around any client-side pre-processing you do.
You could try and use : http://ejohn.org/blog/pure-javascript-html-parser/ .
But if the user is entering the html by hand you could just check to have all tags closed properly. If not, just display an error message to the user.
You can create a jQuery element using the text and then get it's html, like so
Sample
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
Script
alert($($('textarea').text()).html());
alert($($('textarea').text()).html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<div>
<div>
<span>some content</span>
<span>some content
</div>
</textarea>
The simple way to check if entered HTML is actually valid and parseable by browser is to let browser try it out itself using DOMParser. Then you could check if result is ok or not:
function checkHTML(html) {
var dom = new DOMParser().parseFromString(html, "text/xml");
return dom.documentElement.childNodes[0].nodeName !== 'parsererror';
}
$('button').click(function() {
var html = $('textarea').val();
var isValid = checkHTML(html);console.log(isValid)
$('div').html(isValid ? html : 'HTML is not valid!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea cols="80" rows="7"><div>Some HTML</textarea> <button style="vertical-align:top">Check</button>
<div></div>
I'm just trying to do this from the chrome console on Wikipedia. I'm placing my cursor in the search bar and then trying to do document.activeElement.innerHTML += "some text" but it doesn't work. I googled around and looked at the other properties and attributes and couldn't figure out what I was doing wrong.
The activeElement selector works fine, it is selecting the correct element.
Edit: I just found that it's the value property. So I'd like to change what I'm asking. Why doesn't changing innerHTML work on input elements? Why do they have that property if I can't do anything with it?
Setting the value is normally used for input/form elements. innerHTML is normally used for div, span, td and similar elements.
value applies only to objects that have the value attribute (normally, form controls).
innerHtml applies to every object that can contain HTML (divs, spans, but many other and also form controls).
They are not equivalent or replaceable. Depends on what you are trying to achieve
First understand where to use what.
<input type="text" value="23" id="age">
Here now
var ageElem=document.getElementById('age');
So on this ageElem you can have that many things what that element contains.So you can use its value,type etc attributes. But cannot use innerHTML because we don't write anything between input tag
<button id='ageButton'>Display Age</button>
So here Display Age is the innerHTML content as it is written inside HTML tag button.
Using innerHTML on an input tag would just result in:
<input name="button" value="Click" ... > InnerHTML Goes Here </input>
But because an input tag doesn't need a closing tag it'll get reset to:
<input name="button" value="Click" ... />
So it's likely your browsers is applying the changes and immediatly resetting it.
do you mean something like this:
$('.activeElement').val('Some text');
<input id="input" type="number">
document.getElementById("input").addEventListener("change", GetData);
function GetData () {
var data = document.getElementById("input").value;
console.log(data);
function ModifyData () {
document.getElementById("input").value = data + "69";
};
ModifyData();
};
My comments: Here input field works as an input and as a display by changing .value
Each HTML element has an innerHTML property that defines both the HTML
code and the text that occurs between that element's opening and
closing tag. By changing an element's innerHTML after some user
interaction, you can make much more interactive pages.
JScript
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = 'Fred Flinstone';
}
</script>
HTML
<p>Welcome to Stack OverFlow <b id='boldStuff'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
In the above example b tag is the innerhtml and dude is its value so to change those values we have written a function in JScript
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
For instance:
document.getElementById("example").innerHTML = "my string";
This example uses the method to "find" an HTML element (with id="example") and changes the element content (innerHTML) to "my string":
HTML
Change
Javascript
function change(){
document.getElementById(“example”).innerHTML = “Hello, World!”
}
After you clicked the button, Hello, World! will appear because the innerHTML insert the value (in this case, Hello, World!) into between the opening tag and closing tag with an id “example”.
So, if you inspect the element after clicking the button, you will see the following code :
<div id=”example”>Hello, World!</div>
That’s all
innerHTML is a DOM property to insert content to a specified id of an element. It is used in Javascript to manipulate DOM.
Example.
HTML
Change
Javascript
function FunctionName(){
document.getElementById(“example”).innerHTML = “Hello, Kennedy!”
}
On button Click, Hello, Kennedy! will appear because the innerHTML insert the value (in this case, Hello, Kennedy!) into between the opening tag and closing tag with an id “example”.
So, on inspecting the element after clicking the button, you will notice the following code :
<div id=”example”>Hello, Kennedy!</div>
Use
document.querySelector('input').defaultValue = "sometext"
Using innerHTML does not work on input elements and also textContent
var lat = document.getElementById("lat").value;
lat.value = position.coords.latitude;
<input type="text" id="long" class="form-control" placeholder="Longitude">
<button onclick="getLocation()" class="btn btn-default">Get Data</button>
Instaed of using InnerHTML use Value for input types
Not sure if this is an actual problem per se but I'm using Epic Editor to input and save markdown in my GAE application (webpy with mako as the templating engine).
I've got a hidden input element in the form which gets populated by the EpicEditor's content when I submit the form but all the white spaces are replaced by . Is this an intended feature? If I check the same code on the EpicEditor site, it clearly returns spaces instead of so what's different about mine?
<form>
<!-- form elements -->
<input id="content" name="content" type="hidden" value></input>
<div id="epiceditor"></div>
<button type="submit" name="submit" id="submit">submit</button>
</form>
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML; //all the spaces are returned as and breaks are <br>
$('input#content').html(content);
});
</script>
NOTE: I want to save my content as markdown in a TextProperty field my data store and generate the html tags when I retrieve it using marked.js
I'm the creator of EpicEditor. You shouldn't be getting the innerHTML. EpicEditor does nothing to the innerHTML as you write. The text and code you are seeing will be different between all the browsers and it's how contenteditable fields work. For example, some browsers insert UTF-8 characters for spaces some  .
EpicEditor gives you methods to normalize the text tho. You shouldn't ever be trying to parse the text manually.
$('button#submit').click(function(){
var content = editor.exportFile();
$('input#content').html(content);
});
More details on exportFile: http://epiceditor.com/#exportfilefilenametype
P.S. You don't need to do input#content. Thats the same as just #content :)
You can do this if you dont find out why:
<script type="text/javascript">
$('button#submit').click(function(){
var content = editor.getElement('editor').body.innerHTML;
content = content.replace(" ", " ");
$('input#content').html(content);
});
</script>
[EDIT: solved]
I shouldn't be using innerHTML, but innerText instead.
I figured out that Epic Editor uses on all spaces proceeding the first one. This is a feature, presumably.
However that wasn't the problem. ALL the spaces were being converted to , eventually, I realised it occurs when Epic Editor loads the autosaved content from localStorage.
I'm now loading content from my backend every time instead of autosaving. Not optimal, but solves it.
i have an issue with innerHTML and getElementsById(); method but I am not sure if these two methods are the root of the issues i have.
here goes my code :
<script type="text/javascript">
function clearTextField(){
document.getElementsById("commentText").value = "";
};
function sendComment(){
var commentaire = document.getElementById("commentText").value;
var htmlPresent = document.getElementById("posted");
htmlPresent.innerHTML = commentaire;
clearTextField();
};
</script>
and my HTML code goes like this:
<!doctype html>
<html>
<head></head>
<body>
<p id="posted">
Text to replaced when user click Send a comment button
</p>
<form>
<textarea id="commentText" type="text" name="comment" rows="10" cols="40"></textarea>
<button id="send" onclick="sendComment()">Send a comment</button>
</form>
</body>
</html>
So theorically, this code would get the user input from the textarea and replace the text in between the <p> markups. It actually works for half a second : I see the text rapidly change to what user have put in the textarea, the text between the <p> markup is replaced by user input from <textarea> and it goes immediately back to the original text.
Afterward, when I check the source code, html code hasn't changed one bit, given the html should have been replaced by whatever user input from the textarea.
I have tried three different broswer, I also have tried with getElementByTagName(); method without success.
Do I miss something ? My code seems legit and clean, but something is escaping my grasp.
What I wanted out of this code is to replace HTML code between a given markup (like <p>) by the user input in the textarea, but it only replace it for a few milliseconds and return to original html.
Any help would be appreciated.
EDIT : I want to add text to the html page. changing the text visible on the page. not necessarily in the source. . .
There is no document.getElementsById, however there is a document.getElementById. This is probably the source of your problem.
I don't think there is any document.getElementsById function. It should be document.getElementById.
"To set or get the text value of input or textarea elements, use the .val() method."
Check out the jquery site... http://api.jquery.com/val/