Change color of font after specific code - javascript

When a code is typed in like ^1 in a textarea i want the font color of any text after that code to be changed to whatever color the ^1 is assigned to,
As of now i have the following:
<form method="post" action="index.php">
<textarea id="text" onkeypressed="changecolor()"></textarea>
<input type="submit" value="Add">
</form>
javascript:
function changecolor() { //code here }
so basically when i type in ^1 and the color blue is assigned to that code, the text after that code will be in the color blue, but when a second code is typed in; example ^2 the text after that will be the color that is assigned to that code,
I know very well how to insert data into a database, but i need to beable to find a way of getting the raw data; i.e the data that was orginally typed into the textarea with the codes like ^1 and ^2
Help is really appreciated!

You cant target specific fragments of text in a textarea. What you want to do can't be done of my knowing, unless you monitor its content and add an abstract div layer to output styled html from it.
Many wysiwyg text editors do it like this, or use the 'contenteditable' attribute to allow html editing in modern browsers...
You can start like this:
<script type="text/javascript">
var display, input, displayHtml;
function init(){
display = document.getElementById('display');
input = document.getElementById('input');
}
function onContentChange(){
displayHtml = parseContent(this.value);
display.innerHtml = displayHtml;
}
function parseContent(text){
var html = ... // Generate html according to content
return html;
}
document.onload=init;
</script>
html:
<textarea id='input' onkeypress="javascript:onContentChange" />
<div id='display'></div>

Related

How do I make a form's values change a page's CSS in real-time (without having to refresh the page)?

I am attempting to change the CSS on the page as a user types values into a form using javascript. For example - if they type a color value into said field it turns said button to that color. Or changes size if they provide input in the size field. I have not been able to find any examples relating to this. If you could point me to any resources regarding this that would be awesome!
**This is my first post, please let me know if I am doing anything incorrectly.
this input receives code of colors. ff0 - for example
var btn = document.getElementById('btn');
function changeColor(input) {
btn.style.background="#"+input.value;
}
<form>
<input id="inp" type="text" onInput="changeColor(this);">
<button id="btn">Click</button>
</form>
Funny enough this is something I decided to do a few weeks ago, you just create a blank style in the head section of your html page, add an id and use jquery to set the content of the style upon keyup of what ever you decide to use to set the values, e.g.
<pre contenteditable></pre>
<script>
$(document).ready(function(){
$('pre').keyup(function(){
$('#yourstyletagid').html($(this).html());
});
});
</script>
Something like this?
var button = document.getElementById("button");
var b = button.offsetWidth;
function a(input) {
button.style.width = b + input.value + "px";
}
<form>
<input type="number" onchange="a(this);" min="5">
<button id="button">Hello World</button>
</form>

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

Javascript form innerHTML

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/

giving color to substring after javascript split()

i want to print the text entered in textarea with different colors means i am seperating the string with split() method it works fine then i want to print the substrings in textarea with colors how is it possible
<script type="text/javascript">
function init() {
document.getElementById('txtarea2').focus();
}
function setcolor() {
var str=document.getElementById('txtarea2').value;
var str1=str.split(":");
var first= str1[0];
var second=str1[1];
document.getElementById('txtarea1').value= first + second;
document.getElementById('txtarea2').focus();
}
</script>
<body onload="init()">
<textarea id="txtarea1" rows="3" cols="20"></textarea>
<textarea id="txtarea2" rows="3" cols="20" onChange="setcolor()"></textarea>
</body>
please help me
make an empty div and use it to append
<div id="newDiv"></div>
then create and append two different tags to to this div
first = '<a style="color:red">'+first+'</a>';
second = '<a style="color:blue">'+second+'</a>';
document.getElementById("newDiv").innerHTML=first+second;
Do you mean:
document.getElementById('txtarea1').style.color = 'red';
As far as I know, it is not possible to have multiple colors in a single HTML textarea like you want.
You can not have different color text in a textarea.
You would need to use a rich editor to do that.
If the text is not editable, than use a div/pre to output it and color it with normal css tags.

Categories

Resources