Javascript for loop for text substitution - javascript

I try to use for loop as the substitution of list all
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
relaced by
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('editBox'+i));
}
}
but it seems it doesn't work for me. How to correct it?
Below is fully working code without "for loop":
<?xml version="1.0" encoding="ISO-8859-1"?>
<!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" xml:lang="en-US" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> New Document </title>
<meta name="title" content="" />
<meta name="author" content="0xs.cn" />
<meta name="subject" content="" />
<meta name="language" content="zh-cn" />
<meta name="keywords" content="" />
<style type="text/css" >
/* default css rule */
body { font: 12px "Verdana"; }
</style>
<script type="text/javascript" >
// shortcut
function $(s){
return typeof s == 'object'?s:document.getElementById(s);
}
var dEdit = function(el){
var me = this;
this.save = function (txt){
el.innerHTML = txt;
};
this.edit = function (e){
var e = e || event;
var target = e.target || e.srcElement;
if(target.tagName.toLowerCase() == 'input'){
return;
}
var ipt = document.createElement('input');
ipt.value = target.innerHTML;
ipt.onkeydown = function(){
if((arguments[0]||event).keyCode==13){
me.save(this.value);
}
};
ipt.onblur = function(){
me.save(this.value);
};
target.innerHTML = '';
target.appendChild(ipt);
ipt.focus();
};
el.onclick = this.edit;
};
function init(){
new dEdit($('editBox'));
new dEdit($('editBox2'));
new dEdit($('editBox3'));
}
window.onload = init;
</script>
</head>
<body>
<span id="editBox">This is sample text.</span> <br/><br/>
<span id="editBox2">This is sample text 222.</span> <br/><br/>
<span id="editBox3">This is sample text 333.</span>
</body>
</html>

Change the ids on your span tags to "editBox0", "editBox1" and "editBox2". Also, you posted this exact same question not 20-30 minutes ago and someone gave you the correct answer then too.

You need to add # prefix for ID selectors. Change your code to:
function init(){
for(var i = 0; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}

Among other issues like what happens when you call dEdit(...) on an empty jQuery object...
You need a # prefix to select an ID:
$('#editBox2')

Your loop goes from 0 to 1000 and editBoxN is not a valid ID selector, so you end with
new dEdit($('editBox0'));
new dEdit($('editBox1'));
new dEdit($('editBox2'));
...
change first editBox ID, the loop variable and add a hash to the jquery selector to match the IDs
function init(){
for(var i = 1; i < 1000; i++){
new dEdit($('#editBox'+i));
}
}

The problem is the init is throwing an expection on the first value, since 'editBox0' does not exist. To fix this you can wrap each loop iteration in a try/catch.
e.g.
function init(){
for(var i = 0; i < 1000; i++){
try {
new dEdit($('editBox'+i));
} catch (e) {}
}
}
This way, if an id is undefined, the script still runs. Also, you should change <span id="editBox"> for <span id="editBox0"> or <span id="editBox1"> if you intend to have it assigned on the loop.

Related

Javascript cloneNode for adding new elements

what I'm trying to do is. when I click
function runIt(text) {
var counter = 1;
var comment = document.getElementById("name");
comment.innerText = text;
comment.cloneNode(true);
comment.id += counter;
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
I want it to ADD a new element underneath that output "test".
it's keep getting replaced. :(
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>t</title>
</head>
<body>
<p id="name" class="someclass"></p>
</body>
</html>
cloneNode returns the new code, which you can then append to the DOM. Also counter should be defined outside the function and then incremented each time.
var counter = 1;
function runIt(text) {
var comment = document.getElementById("name");
newcomment = comment.cloneNode(true);
newcomment.innerText = text;
newcomment.id += counter;
counter++;
document.querySelector('body').append(newcomment)
}
document.addEventListener("click", function(e){
runIt("test")
}, true);
<p id="name" class="someclass">-</p>

Chrome not reloading object tag after linking to nonexistent file

I have the following index.html. The objective of the javascript below is to reload the #obj element's data tag, so that it can display multiple images. However, it is possible that one of the images I link the buttons to doesn't exist (in this case, #2).
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
What I expect to happen in the following script is this:
The user presses button1, sees apple
User presses button2, sees nothing
User presses button1, sees apple
However, the third step in that doesn't happen - when I try to reload the object's data after linking to a nonexistent file, it stays blank.
As far as I've been able to gather, this happens in Chrome, and for me works in Safari. I must use the object tag, or some other method that allows for interactive SVG.
One solution you could possibily do is to remove and add the node itself to force a hard reset
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data", "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
} else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
Try changing the tag to an <img> and setting the "src" attribute.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("src","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("src", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<img id="obj" style='width: 100px'></img>
</body>
</html>
I provide a sample which helps you to solve your problem by making a fake request to that URL.
Chrome does it to inform. Even if you handle onerror correctly with correct error handling with try-catch and every trick with a void or ( ) that is told to prevent error - you can not fix it. It is out of Javascript control.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg");
}
else {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'file/that/doesnt/exist', false);
request.send();
// the object request will be actually modified
if (request.status === 404) {
alert("The file you are trying to reach is not available.");
}
else
{
object.setAttribute("data", "file/that/doesnt/exist");
}
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.

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>

Can I use an if statement to display the changes in my array (JavaScript)?

I'm trying to make my function displayValues() display each value stored in the array arrValues each time it is called. The array undergoes a change before the second time it is called.
I am having trouble making the output text display the starting values in one
HTML element, and then the updated values in the second element. I am not allowed to have the functions return any value. At the moment my If statement only shows the updated array. I'd like to know what's causing the before element to not be shown?
function start() {
var arrValues = [5, 15, 25, 35, 45, 55, 65];
document.getElementById("msg1").innerHTML="Array values before the update:";
displayValues(arrValues);
updateValues(arrValues);
document.getElementById("msg2").innerHTML="Array values after the update:";
displayValues(arrValues);
}
function displayValues(dispVals) {
var i = 0;
var text = "";
var before = document.getElementById("before");
var after = document.getElementById("after");
while (i < dispVals.length) {
text += dispVals[i] + " ";
i++;
}
if (before == "") {
before.innerHTML=text;
} else if (before != "") {
after.innerHTML=text;
}
}
function updateValues(upVals) {
var i = 0;
while (i < upVals.length) {
upVals[i] = upVals[i] + 10;
i++;
}
}
window.onload = start;
<!DOCTYPE html>
<html lang="en"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="description" content="Updating array values">
<meta name="keywords" content="arrays, display, update">
<meta name="author" content="">
<title></title>
<script src="w8P1.js"></script>
</head>
<body>
<header>
<h2>Arrays</h2>
</header>
<article>
<p><span id="msg1"></span>
<br />
<span id="before"></span>
<br />
<span id="msg2"></span>
<br />
<span id="after"></span>
</p>
</article>
<footer><p>Produced by </p></footer>
</body></html>
You set var before = document.getElementById("before");
So before is the HTML span element, not a string.
You should compare the contents of the span:
if(before.innerHTML == ""){...}
As most of the HTML elements don't have a value, you should use innerHTML.
Change the below line your code.
if (before.innerHTML == "") {
before.innerHTML=text;
} else if (before != "") {
after.innerHTML=text;
}

Why the event doesn't execute?

Hey guys could anyone explain why the event doesn't execute?
The debugger doesn't give any error at all!
Thank you in advance
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<button class="boton">prueba</button>
<body>
<script type="text/javascript">
var elemento= document.getElementsByClassName("boton")
elemento.onclick=function(){
alert("hola");
};
debugger;
</script>
</body>
</html>
The DOM method document.getElementsByClassName() returns an array. You must loop through the array items before assigning the onclick handler:
var elemento = document.getElementsByClassName("boton")
for (var i = 0; i < elemento.length; i++) {
elemento[i].onclick = function() {
alert("hola");
};
}
debugger;
<button class="boton">prueba</button>
Alternatively, if you are selecting only one element, you can use document.querySelector():
var elemento = document.querySelector(".boton");
elemento.onclick = function() {
alert("hola");
};
debugger;
<button class="boton">prueba</button>

Categories