I have 3 data in the JSON file and want each data to be displayed 1 by 1 at a single click.The problem is the previous data was'nt replaced by the new data as the button was click. They ended up being side by side (image below). How do i overcome this? Thanks in advance.
JSON FILE
[
{"quote": "Everyday Is A New Day"},
{"quote": "Trust Your Guts"},
{"quote": "All The Best"}
]
HTML
<p id="text"></p>
<button id="btn">GENERATE</button>
JAVASCRIPT
var text = document.getElementById("text");
var btn = document.getElementById("btn");
var i=0;
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'data2.json');
ourRequest.onload = renderHTML;
ourRequest.send();
});
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
text.insertAdjacentHTML('beforeend', htmlString);
};
instead of
text.insertAdjacentHTML('beforeend', htmlString);
just use
text.innerHTML = htmlString;
insertAdjacentHTML doesn't replace the html.
Instead of using insertAdjacentHTML, set innerHTML directly. So your new function would look like:
function renderHTML(data) {
var htmlString =data[i].quote;
i++;
i %= data.length; // new
text.innerHTML = htmlString; // changed
}
I also inserted the line i %= data.length; so you don't go off the end of the array, and instead loop around to the beginning of data.
Related
I'm taking the content of a textarea and saving it in a variable. But I notice that when I save the content, the variable ignores the spacing (new lines). How do I fix this. I want the variable to store the structure of the text, with all the new lines and tabs. My code in which I save the content from the textarea is below:
let content = document.getElementById('content').value
The whole function is below:
function mail(){
var options = document.getElementById('users').options
let content = document.getElementById('content').value
var emails = []
var regex = /\*user\*/gi
for(var i = 2; i < options.length; i++){
emails.push(options[i].innerHTML)
content = content.replace(regex, emails[i-2])
window.open(`mailto:${emails[i-2]}?subject=To ${emails[i-2]}&body=${content}`)
}
}
Thanks!!! Any help is appreciated!
Actually, spaces and new lines are exists but because you put your content in html (body{}), they are invisible.
some solutions:
let content = document.getElementById('content').value.replace(/\n/g,"<br/>").replace(/ ( +)/g,function(a,b){var s="", i=0; for(;i<b.length;i++)s+=" "; return " "+s;});
or this:
let content = "<pre>"+document.getElementById('content').value+"</pre>"
or this:
let content = "<div style='white-space: pre'>"+document.getElementById('content').value+"</div>"
The above solutions were for when the body is html.
Edit:
I guess this will solve your problem:
let content = escape(document.getElementById('content').value);
The variable does contain new lines if new lines are entered in the textarea. Keep in mind that textarea will wrap the text to fit it so if you see wrapped text, that doesn't mean there is a new line character in the text.
<textarea id="content"></textarea>
<input type="button" value="submit" onclick="msg()">
<script>
function msg() {
let message = document.getElementById('content').value;
alert(message);
}
</script>
I have some simple code that allows you to enter Amazon isbns/asins and converts them to hyperlinks. These hyperlinks are Amazon.com searches for the said isbn/asin.
Example pic: http://imgur.com/a/rYgYt
Instead of the hyperlink being a search I would like the link to go directly to the products offer page.
The desired link would be as follows:
https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used
"ASIN" would be where the ASIN/ISBN would need to be populated to generate the link, for example:
Im asking if someone could help modify my existing code to create the change. My skills lack the ability to implement the change. The existing code is as follows:
<html>
<head>
</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>
<script>
var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base =
'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
var urls = []
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
urls=[];
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item);
container.appendChild(link);
urls.push(base + item);//add the url to our array of urls for button click
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
function openAllUrls(){
for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
window.open(urls[i]);
}
}
handler(); // run on load
</script>
</html>
to modify output URL, replace
var base = ".....';
with
var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';
and replace
base + item
with
basePrefix + item + baseSuffix
I have a text file structured like so...
Hello
.
world
.
.
.
.
its me
I using the following code to read the txt file
<head>
<script type="text/javascript">
function readfileautomatically();
</script>
</head>
<body>
<body onload="readfileautomatically();">
<td id="foo"></td>
<script>
function readfileautomatically () {
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
}
</script>
</body>
Currently with the above I'm able to read the text file and alert the contents. I want to now expand my code and do this.
read foo.txt when page loads
assign line 3 world from the txt file id=line3
assign line 1 hello from the txt file id=line1
So that I can do this:
<td="line3"> world from txt file will be here </td>
<td="line1"> hello from txt file will be here </td>
Any help given would be greatly appreciated.
Let me know if you had any questions :)
<html>
<head>
</head>
<body onload="readfileautomatically();">
<div id="line1"></div>
<div id="line3"></div>
<script>
function readfileautomatically () {
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function()
{
if( client.responseText != '' )
{
var txt = client.responseText.split("\n");
document.getElementById("line1").innerHTML = txt[0];
document.getElementById("line3").innerHTML = txt[2];
}
}
client.send();
}
</script>
</body>
</html>
To split the file into lines, you can try the String#split method, splitting by \n characters (newlines). This would give you an array of lines.
For instance:
var text = client.responseText;
var lines = text.split("\n"); // create array of lines
document.getelementById("line3").innerHTML = lines[2]; // Arrays start at zero
document.getelementById("line1").innerHTML = lines[0];
JSFiddle example
You'll have to split the text on the new line character and iterate through the array. Watch out for variations between newline on different systems
var text = 'Hello\n.\nworld\n.\n.\n.\n.\nits me';
var lines = text.split('\n');
lines.forEach(function (line, i) {
if (line) {
var div = document.createElement('div');
div.id = 'line' + (i + 1);
div.innerHTML = line;
document.body.appendChild(div);
}
console.log('%d: %s', i, line);
});
Code Source
Use this js:
function /*<trigger load function>*/ () {
var client = new XMLHttpRequest();
client.open('GET', '//<path to file>');
client.onreadystatechange = function()
{
var txt = client.responseText.split("\n");
document.getElementById("/*<output variable, include beginning slash>*/").innerHTML = txt[<line, 0-9 style>];
/*<duplicate this line for all lines of the file you would like to read, but dont forget unique numbers>*/
}
client.send();
}
Create a <? id="<output variable>"> tag where you want to display the line. replace "?" with a tag name such as "p", "txt", "div", "xmpl", "rgx" or "<custom>".
"xmpl" and "rgx" are not real tags, they are just preferences, but they have styling in some MT CSS files.
Replace anything enclosed in triangle brackets with the shown type of data. this is not HTML, it's JS.
I have refined the code into pure js code with highlighted modification points.
BTW, you can use "<" and ">" to re-create triangle brackets, and "&" for the ampersand at the beginning. This code is an ampersand, followed by text(case sensitive) to re-create special characters. a full list is available [here][3].
*some links lead to pages that are coming soon.
*some links lead to a network site made by the maker of this post(do you know?).
Try calling .split() with argument RegExp /\b/ , utilize for loop to iterate resulting array , create td element if index of array is 0 : "Hello" , 2 : "world"
<script>
function readfileautomatically() {
var client = new XMLHttpRequest();
client.open("GET", "/foo.txt");
client.onload = function() {
var tr = document.querySelector("table tr");
var res = this.responseText.split(/\b/);
var text = " from txt file will be here";
for (var i = 0; i < res.length; i++) {
if (i === 0) {
var elem = document.createElement("td");
elem.id = "line" + 1;
elem.innerHTML = res[i] + text;
tr.appendChild(elem);
} else if (i === 2) {
var elem = document.createElement("td");
elem.innerHTML = res[i].toLowerCase() + text;
elem.id = "line" + i;
tr.insertBefore(elem, tr.lastChild)
}
}
}
client.send();
}
</script>
<body onload="readfileautomatically();">
<table>
<tbody>
<tr>
<td id="foo">foo</td>
</tr>
</tbody>
</table>
</body>
jsfiddle http://jsfiddle.net/pvd0q36x/
I am trying to output pictures of words based on the users input , i was wondering if there was a way to do it through Loop through an array and concatenate the HTML for the image elements with src's set to the corresponding image?
//myArray
var Signs = new Array("signa.jpg", "signb.jpg", "signc.jpg", "signd.jpg", "signe.jpg", "signf.jpg", "signg.jpg", "signh.jpg", "signi.jpg", "signj.jpg", "signk.jpg", "signl.jpg", "signm.jpg", "signn.jpg", "signo.jpg", "signp.jpg", "signq.jpg", "signr.jpg", "signs.jpg", "signt.jpg", "signu.jpg", "signv.jpg", "signw.jpg", "signx.jpg", "signy.jpg", "signz.jpg");
$(document).ready(function () {
$("#btnGet").click(function () {
var pattern = new RegExp(/^[a-zA-Z]+$/);
var UserInput;
UserInput = $('#txt_name').val();
//splits input
UserInput = UserInput.split("");
//gets data from input
var userFirstName = trim($("#txt_name").val());
text = text.toLowerCase(); //put all text into lower case
});//end of txt_name
});//end of btnGet
//Trim function from http://www.somacon.com/p355.php
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g, "");
}
</script>
You can use code such as the following - this generates the html img tag for each letter and then injects these into a DOM element (assuming, for example, you have a div with id of "output":
var imageTags = $('#txt_name').val().split('').map (function(c) {return '<img src="img' + c + '.png" />';}, '');
$("#output").html(imageTags.join(''));
Here is a sample jsFiddle:
http://jsfiddle.net/zdmmx49k/4/
I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.
Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}
I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there
I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...
This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example