<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
str = "This is an apple and I love it.";
function searching(query){
var patt = new RegExp(query,"gi");
var query = "<span style='color: red'>"+query+"</span>";
document.getElementById("text").innerHTML = str.replace(patt,query);
return str = document.getElementById("text").innerHTML;
}
/*
patt1 = new RegExp("is","gi");
patt2 = /\san\s/gi;
document.write(str.replace(patt2,"<span style='color:red'> are </span>"));
*/
</script>
</head>
<body>
<div id="text"><script>document.write(str)</script></div>
<form>
<input type="text" id="querys" value="" onkeyup="searching(this.value)" />
</form>
</body>
</html>
I want after each search the result replaces the original string with the hightlight (red).
For example,
For the first time, I search "apple".
"apple" is highlighted in the string.
Return the string in the div with the red highlight.
For the second time, I search "is"
"is" is highlighted with red in the string.
I tried to use innerHTML but innerHTML will also return the inline CSS style tags.
I don't understand the purpose of this line:
return str = document.getElementById("text").innerHTML;
Is str being used somewhere else? In that case, you might need to keep two separate variables: one for the original string (which you'll do your searches against) and one for the modified string with the <span> tags.
Related
I have a textarea html element and I want to save its value to a JSON file by stringifying it:
document.querySelector("#button").addEventListener("click", () => {
const rawText = document.querySelector("#textarea").value;
const jsonText = JSON.stringify(rawText);
console.log(jsonText);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<textarea id="textarea" cols="30" rows="10"></textarea>
<button id="button">log json stringified</button>
</body>
</html>
Running the snippet above, we can see two problems:
When the user types in a special character, JSON.stringify() automatically escapes it.
When the user enters a new line, JSON.stringify() adds a \n special character.
How to format the output such that it preserves any special characters that the user types and ignores new lines entered by the user?
For example when user types in:
one\ntwo\tthree\\nfour
five
I want to log:
"one\ntwo\tthree\\nfourfive"
Instead I am currently logging:
"one\\ntwo\\tthree\\\\nfour\nfive"
You could just remove the new lines:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");;
Expanding from Eugen Sunic's answer, the solution is:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");
const jsonText = JSON.stringify(rawText).replace(/\\\\/g, "\\");
I want to access html element by node relationship likes parentNode,fastChild,nextSibling etc.But my following code not work properly.
My Code looks like :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<p>This is first para</p>
<div id="mydiv">
<h2 align="center">This is the Header</h1>
<p align="justify">This is the Paragraph</p>
<marquee scrolldelay="10">This is maquee</marquee>
</div>
<p>This is last para</p>
<script type="text/javascript">
var mydiv = document.getElementById("mydiv");
alert(mydiv.parentNode + "\n" +
mydiv.firstChild + "\n" +
mydiv.childNodes[1] + "\n" +
mydiv.lastChild + "\n" +
mydiv.previousSibling + "\n" +
mydiv.nextSibling);
</script>
</body>
</html>
OUTPUT in alert box looks like :
[object HTMLBodyElement]
[object Text]
[object HTMLHeadingElement]
[object Text]
[object Text]
[object Text]
But for the div,the parentNode,fastChild,childNodes[1],lastChild,previousSibling and nextSibling should be body,h2,p,marquee,p and p.So why output is looks like above?
The whitespace before/after the various elements is turned into text nodes. You can see the results you want if you remove all spaces:
<p>This is first para</p><div id="mydiv"><h2 align="center">This is the Header</h1><p align="justify">This is the Paragraph</p><marquee scrolldelay="10">This is maquee</marquee></div><p>This is last para</p>
Example: http://codepen.io/paulroub/pen/hpIow
The MDN Node.firstChild docs explain this in more detail.
Note that the equivalent jQuery methods will ignore the text nodes and give you the children, next nodes, etc. that you want.
You can also loop over child nodes, skipping text nodes until you find something else:
for ( var i = 0; i < mydiv.childNodes.length; ++i )
{
if (mydiv.childNodes[i].nodeType != Node.TEXT_NODE)
{
firstNon = mydiv.childNodes[i];
break;
}
}
Example: http://codepen.io/paulroub/pen/chLCo
you can use firstElementChild to bypass that whitespace (or just use an existing js library if what are you doing isn't meant just for learning purposes, dealing with the DOM yourself isn't a very pleasant experience)
Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.
Look at the below code, this JavaScript is used to take a string (in a language other than English) and convert it into English.
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var content = document.getElementById('translation');
// Setting the text in the div.
content.innerHTML = '<div id="text">HELLO WORLD<\/div>
<div id="translation"/>';
// Grabbing the text to translate
var text = document.getElementById("text").innerHTML;
// Translate from Spanish to English, and have the callback of
// the request put the resulting translation in the
// "translation" div. Note: by putting in an empty string for
// the source language ('es') then the translation will
// auto-detect the source language.
google.language.translate(text, '', 'en', function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
google.setOnLoadCallback(initialize);
</script>
I want that the string "HELLO WORLD" must be entered by user at run time in a text field and then that string is passed to the div id text. So is this possible?
Hope you are referring to the document below:
http://code.google.com/apis/language/translate/v1/getting_started.html
Please refer to the section "Getting Started" where it says about "Signing up for an API key". This needs to be done before you could implement the code in your page.
Once done, make the modification to the script file which you include in the html page with your key.
Here, replace your key with "MY_KEY_STRING" in the bottom code and get started.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Language API Sample</title>
<script src="https://www.google.com/jsapi?key=MY_KEY_STRING"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
//Show the translate button
document.getElementById("translateButton").style.display = "";
}
google.setOnLoadCallback(initialize);
function translate() {
var text = document.getElementById("fromText").value;
google.language.translate(text, 'es', 'en', function(result) {
var translated = document.getElementById("toText");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
From:<input type="text" id="fromText"/>
To:<span id="toText"></span>
<input type="button" value="Translate" onclick="translate()" style="display: none;" id="translateButton">
</body>
</html>
HTML:
<form id="translate">
<textarea id="translate-me"></textarea>
<input type="submit" />
</form>
JavaScript:
var form = document.getElementById('translate')
var textarea = document.getElementById('translate-me')
form.onsubmit = function () {
google.language.translate(textarea.value, ...)
return false; // prevent default action (form submission)
}
Using jQuery or something similar would make this easier, of course.
This code displays times zones vertically. I would like to display them horizontally but with appropriate spacing. I want to replace the 'br' break tag (second to last line of code) with a tag that will provide spacing between a new name and zone. does not work. Simple but tricky for some reason.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/JavaScript">
//Universal clock 2006
//Genuine code by Corneliu Lucian "KOR" Rusu mailto:corneliulucian(AROND)apropo.ro
var wd=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var D=[
['Bucharest',120,60],//city,standard time zone(minutes), DST(minutes)
['Madrid',60,60],
['New York',-300,60],
['Nairobi',180,0]
]
//add in the array your cities,STZ, DST
function calc(){
var spans=document.getElementById('zonediv').getElementsByTagName('span')
for(var i=0;i<D.length;i++){
var t=new Date();
t.setTime(t.getTime()+(t.getTimezoneOffset()*60000)+((D[i][1]+D[i][2])*60000));//the zone's time
var Dy=t.getFullYear();
var Dd=t.getDate()<10?'0'+t.getDate():t.getDate();
var Dm=t.getMonth()<10?'0'+(t.getMonth()+1):t.getMonth()+1;
var Dh=t.getHours()<10?'0'+t.getHours():t.getHours();
var Di=t.getMinutes()<10?'0'+t.getMinutes():t.getMinutes();
var Ds=t.getSeconds()<10?'0'+t.getSeconds():t.getSeconds();
var Dz=wd[t.getDay()];
spans[i].firstChild.data=Dh+':'+Di+':'+Ds+' - '+Dz+' '+Dd+'/'+Dm+'/'+Dy;
}
setTimeout('calc()',1000)
}
onload=function(){
var root = document.getElementById('zonediv');
for(var i=0;i<D.length;i++){
root.appendChild(document.createTextNode(D[i][0]+' '))
var sp= document.createElement('span');
sp.appendChild(document.createTextNode(' '));
root.appendChild(sp);root.appendChild(document.createElement('br'))
}
calc();
}
</script>
</head>
<body>
<div id="zonediv">
</div>
</body>
</html>
Try replacing
root.appendChild(document.createElement('br'))
with something like
root.appendChild(document.createTextNode(' '))
This would append a space instead of a br element :)