JavaScript function doesn't change the textarea in Chrome&Firefox but works in IE - javascript

I've a web page which include a JavaScript function to convert the multiple lines to a comma separated data. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.innerHTML = ctt;
} else {
incident_box.innerHTML = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>
It works fine in IE:
The line break replaced to comma
But it doesn't working as expected in Chrome and Firefox:
Line break replaced to comma at Dev Tool but it doesn't present on Chrome
Does any one know how to fix it?
Thanks

Use value property. innerHTML is for another purposes. Even textarea has the closing tag, the inner content is the textarea value:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add case</title>
<script type="text/javascript">
function replaceSeperator() {
var incident_box = document.getElementById("TextBoxIncidentID")
var content = incident_box.value;
//incident_box.innerHTML = content.replace(/\n/g, ",");
var ctt = content.replace(/\n/g, ",");
var lastchar = ctt.substr(ctt.length - 1);
if (lastchar != ",") {
incident_box.value = ctt;
} else {
incident_box.value = ctt.substr(0,ctt.length - 1);
}
}
</script>
</head>
<body>
<textarea name="TextBoxIncidentID" rows="2" cols="20" id="TextBoxIncidentID" textwrapping="Wrap" acceptreturn="true" onmouseout="replaceSeperator()" style="font-family:Calibri;font-size:Medium;height:60px;width:430px;margin-top: 5px;"></textarea>
</body>
</html>

You are missing a ; at the end of
var incident_box = document.getElementById("TextBoxIncidentID")
Some browsers are more forgiving to this than others.

Related

How to replace text in a html document using Javascript

I have written this code which I thought was correct, but although it runs without error, nothing is replaced.
Also I am not sure what event I should use to execute the code.
The test a simple template for a landing page. The tokens passed in on the url will be used to replace tags or tokens in the template.
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str) {
return 'Newtext'; // JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t = 0;
var tags = Array('keyword', 'locale', 'advert_ID');
if (document.readyState === 'complete') {
var str = document.body.innerText;
for (t = 0; t < tags.length; t++) {
//replace in str every instance of the tag with the correct value
if (tags[t].length > 0) {
var sToken = '{ltoken=' + tags[t] + '}';
var sReplace = getQueryVar(tags[t]);
str.replace(sToken, sReplace);
} else {
var sToken = '{ltoken=' + tags[t] + '}'
var sReplace = '';
str.replace(sToken, sReplace);
//str.replace(/sToken/g,sReplace); //all instances
}
}
document.body.innerText = str;
}
}
</script>
</head>
<body>
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type="button" onclick="searchReplace('keyword')">
</body>
</html>
So when the documment has finished loading I want to execute this code and it will replace {ltoken=keyword} withe value for keyword returned by getQueryVar.
Currently it replaces nothing, but raises no errors
Your problem is the fact you don't reassign the replacement of the string back to it's parent.
str.replace(sToken,sReplace);
should be
str = str.replace(sToken,sReplace);
The .replace method returns the modified string, it does not perform action on the variable itself.
Use innerHTML instead innerText and instead your for-loop try
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)))
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// gets passed variables frm the url
function getQueryVar(str)
{
return'Newtext';// JUST SCAFFOLD FOR TESTING
}
function searchReplace() {
/**/
var t=0;
var tags =Array('keyword','locale','advert_ID');
if (document.readyState==='complete'){
var str = document.body.innerHTML;
tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ t+'}','g'), getQueryVar(t)));
//tags.forEach(t=> str=str.replace(new RegExp('{ltoken='+ tags[t]+'}', 'g'), getQueryVar(tags[t])));
document.body.innerHTML=str;
}
}
</script>
</head>
<body >
<H1> THE HEADING ONE {ltoken=keyword}</H1>
<H2> THE HEADING TWO</H2>
<H3> THE HEADING THREE</H3>
<P>I AM A PARAGRAPH {ltoken=keyword}</P>
<div>TODO write content</div>
<input type ="button" onclick="searchReplace('keyword')" value="Clicke ME">
</body>
</html>

Convert a HTML Collection to Javascript Array?

I am a newbie, trying to learn w3c-dom, html-dom, just went through this DOM-Introduction
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
While logging this on console, i got just an empty array, when i tried to convert the HTMLCollection to Array.
Note: Tried using for-loop also.
Attached the console output,
Yes, adding
document.addEventListener('DOMContentLoaded', function() { //rest of the code });
fixes the issue
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
});
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
Note: Problem with chrome console is, array values are evaluated on asynchronously.
Thanks to #somethinghere & #trincot.

Regex to replace "t" with "T" only if succeeded by "a","o","u" with javascript

In Javascript I want to replace "t" with "T" but only if the character after the "t" is succeeded by "a","o","u". Eg: String: tatotu, Target String: TaToTu
I couldn't find the Regex.
$(document).ready(function(){
$("#ta_1").keyup(function(event) {
var text = $(this).val();
text = text.replace("t, (\\a|\\o|\\u)","T");
$("#ta_1").val(text);
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="ta_1" rows="5" cols="28" ></textarea>
</body>
</html>
Use an actual regular expression with lookaheads.
$(document).ready(function() {
$("#ta_1").keyup(function(event) {
var text = $(this).val();
text = text.replace(/t(?=a|o|u)/g, "T");
$("#ta_1").val(text);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="ta_1" rows="5" cols="28"></textarea>
</body>
</html>
Simple solution using replace callback:
...
text = text.replace(/(t)(a|o|u)/gi, function(m, p1, p2) {
return p1.toUpperCase() + p2;
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
A simple regex like this would be suffice.
Regex: t(a|o|u)
Replace with: T$1 or T\1
Regex101 Demo
Try this
var map={"ta":"Ta", "to": "To", "tu": "Tu"};
var regex = new RegExp(Object.keys(map).join("|"), "g");
var output = "tatotu".replace(regex, function(matched){return map[matched]});
alert(output);
var str = "tatatou";
var result = str.replace(/t([aou])/g, "T$1");

XRegExp to match Greek whole words

<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<script src="xregexp.js"></script>
<script src="unicode-base.js"></script>
<script src="unicode-scripts.js"></script>
<script>
var wordsToMatch = "Gr|Greek|ΕΛΛΗΝΙΚΑ";
var regexPattern = '\\b('+wordsToMatch+')';
var referenceRegex = new XRegExp(regexPattern, 'mi');
//var testString = "ΕΛΛΗΝΙΚΑ"; //null - ???
var testString = "Gr"; //Gr,Gr - OK AS IT SHOULD
var match = referenceRegex.exec(testString);
function myFunction()
{
alert(match);
}
</script>
</head>
<body onload="myFunction()">
</body>
</html>
I believe my example is quite explainable, it matches fine english words, I would like to match also Greek words too. I am not familiar with the unicode add-on of xregexp, my pattern was implemented to work with regexp.
You need the scripts addon besides the unicode base:
<script src="xregexp.js"></script>
<script src="addons/unicode/unicode-base.js"></script>
<script src="addons/unicode/unicode-scripts.js"></script>
<script>
XRegExp("\\p{Greek}+").test("ΕΛΛΗΝΙΚΑ"); // true
</script>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<script>
var wordsToMatch = "Gr|Greek|ΕΛΛΗΝΙΚΑ";
var regexPattern = '('+wordsToMatch+')';
var referenceRegex = new RegExp(regexPattern, 'mi');
//var testString = "ΕΛΛΗΝΙΚΑ"; //Works now fine
var testString = "Gr"; //Gr,Gr - OK AS IT SHOULD
var match = referenceRegex.exec(testString);
function myFunction()
{
alert(match);
}
</script>
</head>
<body onload="myFunction()">
</body>
</html>
The above works fine. A little bit reading in regular expressions and testing cleared my problem. Removed \b and also XRegExp isn't needed...

Bold text in body using javascript

This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);

Categories