I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>
Related
I want to prompt user to enter a tag and it will list it in the console.log and will ask again until they type "quit". if that happens then I will use the documentwrite to list in the innertext what the previous tags been searched for.
var selector = prompt("Please enter a selector: ");
var selectorr = document.getElementsByTagName(selector);
var breaker = "quit";
breaker = false;
var textlogger = "elements have been found that match the selector ";
var lengthfinder = selectorr.length;
while(true) {
console.log(lengthfinder + textlogger + selector);
if (selector == breaker) {
for (var i=0; i<divs.length; i++) {
document.write.innerText(textlogger);
}
}
}
If you wanna try jQuery and something fun, take this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Loop with jquery deferred</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var loop = function () {
return $.Deferred(function (deferred) {
var selector = prompt("Please enter a selector: ");
var quit = 'quit';
var selectors = [];
while (selector && selector != quit) {
selectors.push(selector);
var elements = $(selector);
console.log(elements.length + " elements have been found that match the selector " + selector);
selector = prompt("Please enter a selector: ");
}
if (selector)
{
deferred.resolve(selectors);
}
else
{
deferred.reject();
}
}).promise();
};
$(function () {
loop().done(function (selectors) {
$($.map(selectors, function (item, index) {
return '<div>' + item + '</div>';
}).join('')).appendTo($('body'));
});
});
</script>
</head>
<body>
<div>
<iframe src="http://stackoverflow.com/questions/40392515/will-this-loop-correctly-and-be-able-to-list-tag-names"/>
</div>
</body>
</html>
Here is the version with comments and suggestions on where to put your necessary code for it to work.
Code Preview
var breaker = "quit",
textlogger = "elements have been found that match the selector ",
textList = new Array();
while (true) {
var selector = prompt("Please enter a selector: ");
if (selector == breaker) {
/*
Write your necessary output here
*/
/*
After output you break out
*/
break;
} else {
/*
Write It inside list
*/
textList.push(selector);
}
/*
Write necessary output in console
*/
console.log(selector);
}
I want to prompt user to enter a tag and it will list it in the
console.log and will ask again until they type "quit"
while ("quit" !== prompt("Tag name selector, type `quit` to exit", "quit")) {
console.log("in loop");
}
console.log("exit loop");
I will use the documentwrite to list in the innertext what the
previous tags been searched for.
Either you use: document.write("some text") to append to existing dom or you can use selectorr[i].innerText="some text"
Here is my small example that might help you:
var selector;
while ("quit" !== (selector = prompt("Tag name selector. Use `quit` to cancel search", "quit"))) {
var elements = document.getElementsByTagName(selector);
var count = elements.length;
while (count--) {
elements[count].innerHTML += " [matched]";
}
}
<span>This is my <span> tag 1</span>
<p>This is my <p> tag 1</p>
<div>This is my <div> tag 2</div>
<p>This is my <p> tag 3</p>
<span>This is my <span> tag 2</span>
I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>
I am trying to get the inner text of HTML string, using a JS function(the string is passed as an argument). Here is the code:
function extractContent(value) {
var content_holder = "";
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === '>') {
continue;
while (value.charAt(i) != '<') {
content_holder += value.charAt(i);
}
}
}
console.log(content_holder);
}
extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");
The problem is that nothing gets printed on the console(*content_holder* stays empty). I think the problem is caused by the === operator.
Create an element, store the HTML in it, and get its textContent:
function extractContent(s) {
var span = document.createElement('span');
span.innerHTML = s;
return span.textContent || span.innerText;
};
alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));
Here's a version that allows you to have spaces between nodes, although you'd probably want that for block-level elements only:
function extractContent(s, space) {
var span= document.createElement('span');
span.innerHTML= s;
if(space) {
var children= span.querySelectorAll('*');
for(var i = 0 ; i < children.length ; i++) {
if(children[i].textContent)
children[i].textContent+= ' ';
else
children[i].innerText+= ' ';
}
}
return [span.textContent || span.innerText].toString().replace(/ +/g,' ');
};
console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>. Nice to <em>see</em><strong><em>you!</em></strong>"));
console.log(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>. Nice to <em>see</em><strong><em>you!</em></strong>",true));
One line (more precisely, one statement) version:
function extractContent(html) {
return new DOMParser()
.parseFromString(html, "text/html")
.documentElement.textContent;
}
textContext is a very good technique for achieving desired results but sometimes we don't want to load DOM. So simple workaround will be following regular expression:
let htmlString = "<p>Hello</p><a href='http://w3c.org'>W3C</a>"
let plainText = htmlString.replace(/<[^>]+>/g, '');
use this regax for remove html tags and store only the inner text in html
it shows the HelloW3c only check it
var content_holder = value.replace(/<(?:.|\n)*?>/gm, '');
Try This:-
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function extractContent(value){
var div = document.createElement('div')
div.innerHTML=value;
var text= div.textContent;
return text;
}
window.onload=function()
{
alert(extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>"));
};
</script>
</body>
</html>
For Node.js
This will use the jsdom library, since node.js doesn't have dom features as in browser.
import * as jsdom from "jsdom";
const html = "<h1>Testing<h1>";
const text = new jsdom.JSDOM(html).window.document.textContent;
console.log(text);
Use match() function to bring out HTML tags
const text = `<div>Hello World</div>`;
console.log(text.match(/<[^>]*?>/g));
You could temporarily write it out to a block level element that is positioned off the page .. some thing like this:
HTML:
<div id="tmp" style="position:absolute;top:-400px;left:-400px;">
</div>
JavaScript:
<script type="text/javascript">
function extractContent(value){
var div=document.getElementById('tmp');
div.innerHTML=value;
console.log(div.children[0].innerHTML);//console out p
}
extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");
</script>
Using jQuery, in jQuery we can add comma seperated tags.
var readableText = [];
$("p, h1, h2, h3, h4, h5, h6").each(function(){
readableText.push( $(this).text().trim() );
})
console.log( readableText.join(' ') );
you need array to hold values
function extractContent(value) {
var content_holder = new Array();
for(var i=0;i<value.length;i++) {
if(value.charAt(i) === '>') {
continue;
while(value.charAt(i) != '<') {
content_holder.push(value.charAt(i));
console.log(content_holder[i]);
}
}
}
}extractContent("<p>Hello</p><a href='http://w3c.org'>W3C</a>");
I'm using the below in a javascript Q & A chatbot. To answer for example "what is AG in the periodic table? Answer is Silver.
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (i = 0; i < Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
}
return true;
}
Then I have in another file the array laid out like this:
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitrogen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
My problem is because the table symbols are only 1 or 2 letters it's matching a lot of wrong things. How can I set this up where "only" b matches boron, be matches beryllium. etc I've looked a word boundaries but can seem to figure out how to use them here.
Instead of this code block which is checking if input contains a symbol:
if (input.indexOf(Periodic_Table[0]) != -1) {
document.result.result.value = Periodic_Table[1];
}
You should check for equality like this:
Periodic_Tables=new Array("h=Hydrogen",
"he=Helium", "li=Lithium", "be=Beryllium", "b=Boron", "c=Carbon", "o=Oxygen",
"f=Fluorine", "ne=Neon", "na=Sodium", "mg=Magnesium", "ag=Silver");
function Parse(input) {
input=input.toLowerCase();
input=input.replace(/[!|?|,|.]/g,"");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
var words=input.split(" ");
var result = "Hmmmm, I don't know. Try Google!";
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
for (var w=0; w<words.length; w++) {
for (i=0; i<Periodic_Tables.length; i++) {
Periodic_Table = Periodic_Tables[i].split('=');
if (words[w] == Periodic_Table[0]) {
result = Periodic_Table[1];
return result;
}
}
}
}
return result;
}
alert(Parse("what is h in periodic table"));
DEMO: http://jsfiddle.net/MnyFP/1/
First i'd use 2d array to store your periodic tables, so that you don't have to string split every time you want to use it.
Instead of
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitrogen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver",
);
Use
Periodic_Tables = [
["h", "Hydrogen"],
["he", "Helium"],
...
]
Assuming that the question is well formatted, that the symbol "AG" has a space in front and after it. I think you could simple test the input against " AG ", or " ag ", if you make it case insensitive. Including the spaces in the test string will for it to find matches that is a word in it self, instead of part of another word.
Pretty use regex has similar abilities, but i am not sure how to do it with regex..
assuming that the question in the chat box ends with the name of the element, u can split the string at the punctuations.(lets say user enters, what is,ag)
function abc(str)
{
String[] parts = str.split("\\W+");
var len=parts.length();
String sub=parts[len-1];
var re=new RegExp("^"+sub+"$","i");
and then use a loop and check the condition
if(re.test(arr[i])){
document.write(arr[i]);
break;
}
}
I would use an array of objects:
Periodic_Tables = [
{Symbol: "h", Element: "Hydrogen"},
{Symbol: "he", Element: "Helium"}
...
]
Then your loop looks like this:
for (i = 0; i < Periodic_Table.length; i++) {
if (input.indexOf(Periodic_Table[i].Symbol) !== -1) {
document.result.result.value = Periodic_Table[i].Element;
}
}
This prevents having to use a regex or a 2d array, and is a little more readable.
I can't seem to get anything to work within the Q and A bot. So I put up a demo here:
http://www.frontiernet.net/~wcowart/aademo.html
Or here is the code: I tried many of the various answers presented. Maybe I'm not implementing them right.
<HTML>
<HEAD>
<TITLE>ChatterBot Page</TITLE>
<script language="JavaScript">
Periodic_Tables=new Array(
"h=Hydrogen",
"he=Helium",
"li=Lithium",
"be=Beryllium",
"b=Boron",
"c=Carbon",
"n=Nitrogen",
"o=Oxygen",
"f=Fluorine",
"ne=Neon",
"na=Sodium",
"mg=Magnesium",
"ag=Silver"
);
var message = new Array();
var randomnum;
var flagrandom;
function Parse() {
var input = new String(document.chat.input.value);
document.chat.input.value="";
input=input.toLowerCase();
word=input.split(" ");
num_of_words=word.length;
input=input.replace(/[!|?|,|.]/g,"");
word=input.split(" ");
if (input.search(/\bu\b/)!=-1) input=input.replace(/\bu\b/,"you");
if (input.search(/\br\b/)!=-1) input=input.replace(/\br\b/,"are");
if (input.search(/\bk\b/)!=-1) input=input.replace(/\bk\b/,"ok");
if (input.search(/\by\b/)!=-1) input=input.replace(/\by\b/,"why");
if ((input.search("(what is|what's)") != -1) && (input.search("(periodic table)") != -1)) {
document.result.result.value = "Hmmmm, I don't know. Try Google!";
for (var i = 0, len = Periodic_Tables.length; i < len; i++) {
if (Periodic_Tables[i].match('^'+input+'=')) {
document.result.result.value = Periodic_Tables[i].split('=')[1] }
}
return true;}
if (!flagrandom) {
randomnum = [Math.floor(Math.random()*3)]
flagrandom=true;}
message[0] = "Sorry, you stumped me on that one.";
message[1] = "Sorry, a search of my data base comes up empty.";
message[2] = "Not sure";
document.result.result.value = message[randomnum];
randomnum++
if (randomnum>2){randomnum=0}
return true;}
</script>
</head>
<BODY BACKGROUND="FFFFFF" TEXT="#0000cc" LINK="#FFCOOO" ALINK="#FFCC99"
VLINK="#FFC000" marginwidth="0" leftmargin="0" topmargin="0" rightmargin="0">
<Center>
<font size="+3">
ChatterBot
</font>
<br>
<img src="botpix.jpg" border="0" WIDTH="200" HEIGHT="200">
<br>
<form name="result">
<textarea rows=5 cols=40 input type="text" name="result">
</textarea><br>
</form>
</center>
<form name="chat" onSubmit="Parse();return false">
<b>Type here:</b>
<input type="text" name="input" size="100">
</form>
</body>
</html>
I need to import some formatted html text in a input textarea value
i use jquery
so what's the best way to do it?
i guess first off i need to replace the then strip out the rest (bold, italic, images etc..)
In my first response I didn't see that you wanted to retain line breaks, so here's a better version. It replaces br with an unlikely string %%br%% and then at the end replaces them with new line (\n). So if that string actually appears in the text, it will be replaced by a new line. You can change that to anything you like, just make it something that is unlikely to be encountered in the text.
<script>
function removeMarkup(m) {
var d = document.createElement('div');
d.innerHTML = m;
var c = 0;
// Make brString something that should never appear in the text
// and has no special meaning in a RegExp
var brString = '%%br%%'
var re = new RegExp('\\s*' + brString + '\\s*','g');
function getTextWithReturns(node) {
var tag = node.tagName && node.tagName.toLowerCase();
var nodes = node.childNodes;
var type = node.nodeType;
var s = '';
// Deal with br
if (tag == 'br') {
return brString;
}
if (nodes && nodes.length) {
for (var i=0, iLen=nodes.length; i<iLen; i++) {
s += getTextWithReturns(nodes[i]);
}
} else if (type == 3 || type == 4) {
s += node.nodeValue
}
return s;
}
return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n');
}
function reduceWhitespace(s) {
return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');
}
</script>
<div id="d0">some text <i>more</i> text
<p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p>
<p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p>
</div>
<form>
<textarea id="ta0" rows="10" cols="50"></textarea>
<button type="button" onclick="
var ta = document.getElementById('ta0');
var div = document.getElementById('d0');
ta.value = removeMarkup(div.innerHTML);
">Set value</button><input type="reset">
</form>
$("#my_textarea").change(function(){
var cleanText = $("<span />").html(this.value);
this.value = cleanText.text();
});
Example: http://jsfiddle.net/6WbXN/