Insert new code to page using JS, with variables - javascript

I need to choose values in three text forms (a,b,c), for ex. 1,2,3. Then click ADD, and it will insert code like this:
<mycode a="1" b="2"><newone c="3"></newone></mycode>
How can I do it? For a while trying different approaches.
Using this code I can add new element to the page
<p> <span id="mytext">click here</span></p>
<script type="text/javascript">
function EditText() {
document.getElementById('mytext').innerHTML = '<mycode a="1" b="2"><newone c="3"></newone></mycode>';
}
</script>
But how can I edit a, b and c values using text-form?
Thank you very much!

Assuming you would also like to be able to pass the values for a, b and c to the function and output them in the newly created DOM. You could do something like the following:
function EditText(aVal, bVal, cVal) {
document.getElementById('mytext').innerHTML = '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}
Appending additional elements each click:
function EditText(aVal, bVal, cVal) {
var currentInnerHtml = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = currentInnerHtml + '<mycode a="'+aVal+'" b="'+bVal+'"><newone c="'+cVal+'"></newone></mycode>';
}

If you have three textareas on the screen, you can get their values using JavaScript and then add them in your string instead of hardcoding them.
<textarea id="textA" cols="30" rows="10"></textarea>
<textarea id="textB" cols="30" rows="10"></textarea>
<textarea id="textC" cols="30" rows="10"></textarea>
<p> <span id="mytext">click here</span></p>
<script>
function EditText() {
var textA = document.getElementById('textA').value;
var textB = document.getElementById('textB').value;
var textC = document.getElementById('textC').value;
document.getElementById('mytext').innerHTML = '<mycode a="' + textA + '" b="' + textB + '"><newone c="' + textC + '"></newone></mycode>';
}
</script>

Related

Appending HTML inputs using JavaScript gives "undefined" value

I have a small code trying to append values using HTML inputs to the same document.
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
<script type="text/javascript">
var child = document.getElementById("text").value;
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para' + toString(child) + '</p>');
}
</script>
the variable child dose not take the text value from the input, which outputted as `undefined'
image 1: typed Test
Image 2: Clicked the Button
how to get the value form the input as New ParaTest?
Code Edited using the answer.
You don't need toString() method, remove it.
Get the reference of element in the child variable and get the value the func()
var child = document.getElementById("text");
function func() {
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend', '<p> New Para: ' + child.value + '</p>');
}
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
child variable needs to assign inside func function and don't need toString()
try this
function func(){
var h = document.getElementById('myh');
let child = document.getElementById("text").value;
h.insertAdjacentHTML('afterend','<p> New Para' + child + '</p>');
}
<html>
<body>
<h2 id="myh"> Header</h2>
<input type="text" id="text">
<button onclick="func()">Append</button>
</body>
</html>
Your variable should be global. Try taking it inside the function and then check it.
function func(){
var child = document.getElementById("text").value;
var h = document.getElementById('myh');
h.insertAdjacentHTML('afterend','<p> New Para' + toString(child) + '</p>');
}

"Writing" inside a HTML page using JS and JS scope

I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>

Javascript - Replacing multiple strings in a text box

I'm trying to create a sort of "find and replace" system for my users to paste their current html and replace another website's urls with another's. Basically, i need files.enjin.com/(6 digit unique code) to be replaced with advena.io/. This is what I have already (i'm using a random's image as a temporary example):
<button id="replace">Replace</button>
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
var mapping = {};
mapping['http://files.enjin.com/' + /(......)/i'] = 'https://advena.io/<?php echo $domain1 ?>/';
document.getElementById('replace').addEventListener('click', function(evt) {
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>
I know that the problem is with the expression that I'm trying to use in the first mapping. I don't know what else to use. I'm not so good with Javascript.
Thankyou in advance to anyone that can help.
Edit: I need this script to be able to change multiple occurrences of the specified mapping.
I figured it out myself. For anyone interested in the answer, here is my solution:
<button id="replace">Replace</button>
<input type="text" id="enjid" placeholder="ie. 435613">
<p>
Original Text:
<textarea id="input">http://files.enjin.com/435613/slider_images/slide1_1920x200.png</textarea>
</p>
<p>
New Text:
<textarea id="output"></textarea>
</p>
<script>
document.getElementById('replace').addEventListener('click', function(evt) {
var mapping = {};
var id = document.getElementById("enjid").value;
mapping['http://files.enjin.com/' + id + '/'] = 'https://advena.io/<?php echo $domain1 ?>/';
mapping['PHP'] = 'Personal Home Page';
mapping['JS'] = 'JavaScript';
var newString = (function(map, oldString) {
Object.keys(map).forEach(function(key) {
oldString = oldString.replace(new RegExp('\\b' + key + '\\b', 'g'), map[key]);
});
return oldString;
}(mapping, document.getElementById('input').value));
output.value = newString;
});
</script>

Need to activate JS code on leaving a textarea

Currently I clean text in a TextArea via an an OnClick event on the submit button of a form.
<textarea id="comment" class="CleanHTML" cols=70 rows=5></textarea>
<button type="submit" id="btn" name="btn" value="Save" onClick='document.getElementsByClassName("CleanHTML")[0].value = cleanWordClipboard(document.getElementsByClassName("CleanHTML")[0].value)'>Save</button>
However I now think this is flawed, and it would be much better to have the cleanHTML function being triggered on the TextArea element itself when say the user leaves it, so if the user pastes some code then moves on, then it will get triggered.
What would be the required event and what would the function call code now look like? I provide a starter below with pseudocode in the onblur event, if onblur is the correct event?
<textarea id="comment" cols=70 rows=5 onblur="this.value=cleanWordClipboard(this.value)"></textarea>
Also what is the best approach to link up all TextAreas to behave this way, centrally. Currently I am thinking that I need to put the required event call on every TextArea.
EDIT1
<script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
return output;
}
</script>
onBlur is the correct event - it triggers when the element loses focus.
Edit:
<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)"></textarea>
<script language="JavaScript">
// Thanks to Johnathan Hedley for this code.
var swapCodes = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230); // dec codes from char at
var swapStrings = new Array("--", "--", "'", "'", "\"", "\"", "*", "...");
function cleanWordClipboard(input) {
// debug for new codes
// for (i = 0; i < input.length; i++) alert("'" + input.charAt(i) + "': " + input.charCodeAt(i));
var output = input.value;
for (i = 0; i < swapCodes.length; i++) {
var swapper = new RegExp("\\u" + swapCodes[i].toString(16), "g"); // hex codes
output = output.replace(swapper, swapStrings[i]);
}
input.value = output;
}
</script>
<textarea id="comment" cols=70 rows=5 onblur="cleanWordClipboard(this)" />
With your JavaScript being:
function cleanWordClipboard(control) {
control.value = "";
}
in regards to your last question:
"Also what is the best approach to link up all TextAreas to behave this way, centrally. Currently I am thinking that I need to put the required event call on every TextArea."
You can use JQuery to help you out here.
<textarea id="commentA" cols=70 rows=5></textarea>
<textarea id="commentB" cols=70 rows=5></textarea>
<script>
$("textarea").blur(function(){
cleanWordClipboard(this);
});
</script>
Here's a very crude example of it running: http://jsfiddle.net/CatmanDoes/p755m0n8/
I would recommend you don't use it to blindly target all textareas but instead do something like this:
<textarea id="commentA" cols=70 rows=5 class="textarea-cleanp"></textarea>
<textarea id="commentB" cols=70 rows=5 class="textarea-cleanp"></textarea>
<script>
$(".textarea-cleanp").blur(function(){
cleanWordClipboard(this);
});
</script>
Whether there's an actual css class for textarea-cleanp doesn't matter

Javascript no jquery - How do I add this function to existing javascript that is triggered by onload / onpaste?

This is an add-on to my previously answered question.
question 8423472
I have tried to implement a validate function to this wonderful code to no avail.
Looks like I need more hand holding here.
This script is a slightly modified version of the quite excellent answer I received from #Martin Jespersen.
The script takes a single column list of emails and breaks it up into textareas containing single row comma delimited lists of no more than 150 addresses. Nice.
Below works great but, I need to add a basic validation function.
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
document.getElementById('t').onpaste = onpaste;
}
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
HOWEVER, the guy I made it for (actually #Martin made it) is not real meticulous about what he pastes into the textarea.
So, I am trying to implement a function that will reduce invalid emails / bad input.
I tried several ways including changing the onload event to a button in the page with onclick event.
I thought I was learning here but, I just can't wrap my brain around what I am doing wrong.
So, how can I insert this function, or just its' "validation" routine into one of the above functions?
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
Useage of findEmailAddresses function:
<textarea name=t rows=10 cols=50 onBlur="this.form.email.value=findEmailAddresses(this.value);"></textarea>
I tried calling the function individually in the functions above and even tried removing the function just inserting the code using "emails" instead of "this.value" in both cases. I even tried a two page approach. For some reason, I just can't implement this code into the working splitter. My results are either no effect or I break the thing.
Basically I tried many variations of inserting. Like below:
<html>
<head>
<script language=javascript type='text/javascript'>
function onpaste(e) {
var t = this;
var cnt='0';
setTimeout(function(){
var list = document.getElementById('t');
var emails= t.value.split(/\s+/), ta;
//
findEmailAddresses(emails);
// also tried inserting code from function. ///
while(emails.length) {
cnt++;
ta = document.createElement('textarea');
ta.value = emails.splice(0,150).join(',').replace(/,\s*$/,'');
document.body.appendChild(ta);
}
document.getElementById('button1').value=cnt;
},1);
}
window.onload = function() {
// tried to trigger it here as well and even added a new split //
document.getElementById('t').onpaste = onpaste;
}
/////
function findEmailAddresses(StrObj) {
var separateEmailsBy = '\n';
var email = "<none>"; // if no match, use this
var emailsArray = StrObj.match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi); // yeah could be better
if (emailsArray) {
email = "";
for (var i = 0; i < emailsArray.length; i++) {
if (i != 0) email += separateEmailsBy;
email += emailsArray[i];
}
}
return email;
}
////////
</script>
</head>
<BODY>
<p><textarea id="t" rows="10" cols="50" class="textarea"></textarea><br /></p><br />
There are <input type="button" id="button1" value="0"> textareas
<pre id="p" class="pre"></pre>
</body>
</html>
Much thanks to anyone who can assist.
Try putting return true; after your inline javascript.

Categories