Javascript form innerHTML - javascript

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/

Related

Form using Javascript exclusively

I have an assigment, I don't understand it as i'm beginner.
Create a javascript script which will modify the DOM of a web-page.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?".
Thank you in advance.
I need to use only Javascript for this and I can only find answers
that use HTML
Web applications use HTML to contain, render and display elements in the viewport (browser window).
Where do you intend to render the form and capture user input?
You can build the DOM structure using JavaScript alone, however, there will still be a HTML file, which will contain the HTML elements created using javascript.
Please provide clarity as to your desired goal and what type of application this is being used for.
My gut feeling, for simplicity, is that you will require to use HTML as your template file, and JavaScript for interactivity and manipulation of the HTML file.
The script must add a form with 4 elements: name, email, message(textarea) and submit button. Each element must contain a label with its name. For example, name field is input type, you must create still from javascript a label named "Name", same for the others except submit button. Also, each laber must have a colour added from javascript(red, blue, yellow). When you click submit button, it must have an alert: "Are you sure you want to send this message?". That's it.
This is a start, just to try to help you to understand the concepts.
I do, however, implore you to go and explore with confidence - you won't break anything, just give it a try!
I recommend you try taking a look at some of these articles, have a look at my (very rudimentary) code below, and feel free to ask any questions you have!
JS:-
W3 Schools JS and HTML reference
HTML:-
W3 Schools: HTML Forms
W3 Schools: Label Tag
W3 Schools: Text Area Tag (This has been left out of the solution on purpose - give it a try!!)
(function divContent() {
//Create a 'div' as a container for our form
var div = document.createElement('div');
// Perhaps you could style it later using this class??
div.className = 'row';
// I have used backticks to contain some more normal looking HTML for you to review, it's not complete though!!
div.innerHTML = `<form action="javascript:" onsubmit="alert('Your message here, or, run a function from your JavaScript file and do more stuff!!')">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="Mickey Mouse">
<br>
<label for="email">Email:</label>
<input type="text" name="email" id="email" value="mickey#mouse.co.uk">
<br><br>
<input type="submit" value="Submit">
</form> `
// Get the body of the document, and append our div containing the form to display it on page
document.getElementsByTagName('body')[0].appendChild(div);
}());
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="CoderYen | Wrangling with 0s & 1s Since The Eighties">
</head>
<body>
</body>
</html>

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?
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>

How to validate or wrap user inputted HTML to fix unclosed tags

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>

What is innerHTML on input elements?

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

EpicEditor text showing as instead of space

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 &nbsp.
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.

Categories

Resources