Hello here I'm trying to Output my function on two separate divs in my project but if I simply output the same I'd it cancels the whole code and nulls the output here is the code.
<script>
function randomString() {
//initialize a variable having alpha-numeric characters
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var string_length = 10;
var randomstring = '';
//put a loop to select a character randomly in each iteration
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
//display the generated string
document.getElementById("randomfield").innerHTML = randomstring;
}
</script>
Then on the body I use
<body onload="randomString();">
<div>
<p id="randomfield"></p>
</div>
</body>
The thing is I want to Output the same string on the page but on a different div maybe at the footer but if I proceed to add
<body onload="randomString();">
<div>
<p id="randomfield"></p>
</div>
<hr>
<footer>
<p id="randomfield"></p>
</footer>
</body>
On the same page it cancels the whole code and nullifies the output. How do I fix this i barely have knowledge of Js
You are using the same id in both areas. You have to specify different id to have them work:
function randomSSSSSString() {
//initialize a variable having alpha-numeric characters
var charssssss = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var sssssstring_length = 10;
var randomsssssstring = '';
//put a loop to select a character randomly in each iteration
for (var i = 0; i < sssssstring_length; i++) {
var rrrrrrnum = Math.floor(Math.random() * charssssss.length);
randomsssssstring += charssssss.substring(rrrrrrnum, rrrrrrnum + 1);
}
//display the generated string
document.getElementById("rrrrrrandomfield").innerHTML = randomsssssstring;
document.getElementById("rrrrrrandomfield2").innerHTML = randomsssssstring;
}
<body onload="randomSSSSSString();">
<div>
<p id="rrrrrrandomfield"></p>
</div>
<hr>
<footer>
<p id="rrrrrrandomfield2"></p>
</footer>
</body>
This is happening because you're using same "id" more than once, which is not valid.
You can change the id to class instead and can use querySelectorAll to loop through each element consisting of that class to display your result.
function randomSSSSSString() {
//initialize a variable having alpha-numeric characters
var charssssss = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
//specify the length for the new string to be generated
var sssssstring_length = 10;
var randomsssssstring = '';
//put a loop to select a character randomly in each iteration
for (var i=0; i<sssssstring_length; i++) {
var rrrrrrnum = Math.floor(Math.random() * charssssss.length);
randomsssssstring += charssssss.substring(rrrrrrnum,rrrrrrnum+1);
}
//display the generated string
var i_want_show_here = document.querySelectorAll(".rrrrrrandomfield")
Array.prototype.forEach.call(i_want_show_here, function(el) {
el.innerHTML = randomsssssstring
});
}
<body onload="randomSSSSSString();">
<div>
<p class="rrrrrrandomfield"></p>
</div>
<hr>
<footer>
<p class="rrrrrrandomfield"></p>
</footer>
</body>
I think you can solve this by creating dynamic p tag with same id. There is no var datatype in javascript change it to let.
function randomString() {
let characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
let randnum = document.getElementById("randnum")
let stringLength = 10;
let tempRandomString = '';
for (let i = 0; i < stringLength; i++) {
let randNum = Math.floor(Math.random() * characters.length);
tempRandomString += characters.substring(randNum, randNum + 1);
}
for (var i = 0; i < 2; i++) {
const elem = document.createElement(`p`);
elem.id = tempRandomString;
elem.innerText= tempRandomString;
randnum.appendChild(elem);
}
}
<html>
<title>Web Page</title>
<head>
</head>
<body onload="randomString();">
<div id="randnum">
</div>
</body>
</html>
Related
I am struggling a bit with this random image javascript even though I sense the answer is quite simple. My code generates four letters (images) at a time. How do I get the code to regenerate new letters instead of adding four additional letters (images)?
Here is a Jsfiddle also.
<script>
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
You can add document.getElementById('result').innerHTML = "" before your for loop to clear the result div before adding 4 new items.
You can also reduce your code a lot by using a for loop to generate the image URLs.
var letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
for (let i = 0; i < letters.length; i++) {
randomImage.push(`http://www.englishclass.dk/_themes/englishclass/img/scrabble/${letters[i]}.png`)
}
document.getElementById('result').innerHTML = " " before for loop
<script>
function getRandomImage() {
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
document.getElementById("result").innerHTML="";
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
Add following code at starting of the function definition :
document.getElementById("result").innerHTML = "";
Like this
<script>
function getRandomImage() {
document.getElementById("result").innerHTML = "";
//declare an array to store the images
var randomImage = new Array();
//insert the URL of images in array
randomImage[0] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/a.png";
randomImage[1] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/b.png";
randomImage[2] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/c.png";
randomImage[3] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/d.png";
randomImage[4] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/e.png";
randomImage[5] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/f.png";
randomImage[6] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/g.png";
randomImage[7] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/h.png";
randomImage[8] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/i.png";
randomImage[9] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/j.png";
randomImage[10] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/k.png";
randomImage[11] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/l.png";
randomImage[12] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/m.png";
randomImage[13] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/n.png";
randomImage[14] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/o.png";
randomImage[15] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/p.png";
randomImage[16] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/q.png";
randomImage[17] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/r.png";
randomImage[18] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/s.png";
randomImage[19] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/t.png";
randomImage[20] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/u.png";
randomImage[21] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/v.png";
randomImage[22] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/w.png";
randomImage[23] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/x.png";
randomImage[24] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/y.png";
randomImage[25] = "http://www.englishclass.dk/_themes/englishclass/img/scrabble/z.png";
//loop to display five randomly chosen images at once
for (let i=0; i< 4; i++) {
//generate a number and provide to the image to generate randomly
var number = Math.floor(Math.random()*randomImage.length);
//print the images generated by a random number
document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="height:150px";/>';
}
}
</script>
<body>
<h1> GENERATE YOUR LETTERS... </h1>
<!-- call user-defined getRandomImage function to generate image -->
<center><button onclick = "getRandomImage()" class="btn btn-white btn- animate">Let's Go!</button></center>
<br> <br>
<span id="result" align="center"> </span>
As explained in "innerHTML += ..." vs "appendChild(txtNode)" appending new elements by doing innerHTML += '<img />' causes the browser to rebuild the entire container. This may cause performance issues depending on where, when and how often you call it. For the sake of completeness I'm providing the more performant example (a bit more verbose but in general better practice).
This should replace your for loop:
// Clear all childs from the container
const container = document.getElementById("result");
container.childNodes.forEach((child) => child.remove());
for (let i = 0; i < 4; i++) {
const number = Math.floor(Math.random() * randomImage.length);
// Create a new <img /> element and append it to the container
const image = document.createElement("img");
image.src = randomImage[number];
image.style.height = "150px";
container.append(image);
}
You can also get a random letter without splitting a string by using the method given in the top voted answer here. You can then simplify your code as the others have mentioned above to only a few lines.
I've commented the code below.
// Function triggered with onclick event
function getRandomImage() {
// Clear the previous letters
document.getElementById("result").innerHTML = "";
// Loop
for (let i = 0; i < 4; i++) {
// Generate random letter
letter = String.fromCharCode(97 + Math.floor(Math.random() * 26))
// Add image to #result
document.getElementById("result").innerHTML += '<img src="http://www.englishclass.dk/_themes/englishclass/img/scrabble/' + letter + '.png" style="height:150px";/>';
}
}
<h1> GENERATE YOUR LETTERS... </h1>
<center>
<button onclick="getRandomImage()" class class="btn btn-white btn-animate">
Let's Go!
</button>
</center>
<br>
<br>
<span id="result" align="center"> </span>
So I have my code so far producing the images and selecting a random word from an array list and producing the right number of images for characters in my random chosen word. My issue is that how do I check the exact input from a textbox when a button is clicked to see if the letter in the textbox is in the string and if so replace the correct image with the letter. If not have the letter show up to the side showing that is was already guessed.
function change(){
check();
}
function check(){
var a = document.getElementById("input").value;
var num = Math.floor(Math.random() * 4);
var words = ["cat", "dog", "fish", "bird"];
var select = words[num];
var low = select.toLowerCase();
alert(select);
for(var b = 0; b < select.length; b++){
var element = document.getElementById("main");
var img = document.createElement("IMG");
img.setAttribute("src", "https://vignette.wikia.nocookie.net/yugioh/images/e/e5/Back-EN.png/revision/latest?cb=20100726082133");
element.appendChild(img);
}
for(var i = 0; i < low.length; i++){
if(low.charAt(i) != low){
var para = document.createElement("P");
var node = document.createTextNode(a + " ");
para.appendChild(node);
var element = document.getElementById("main");
element.appendChild(para);
}
else if(low.charAt(i) == low){
var element = document.getElementById("main");
img.setAttribute("src", "a");
element.appendChild(img);
}
}
}
img{
width: 100px;
}
<body onload='change()'>
<script src="index.js"></script>
<div id="main">
<input type="text" placeholder="Guess" id="input">
<button onclick='clickCheck()'>Click</button>
</div>
</body>
I do not want any jquery.
If you want to do this using the Javascript then you can do it like this
<button id="abc" onClick="myFunction()">Click</button>
<script>
function myFunction() {
//your code here to do what you want to
}
</script>
or
<script>
document.getElementById("#abc").addEventListener("click", function(){
//your code here
});
</script>
I am looking to create a function asking the user for how many numbers must be generated randomly in a series of 200 numbers i.e from 0 to 200.
THanks
Maybe it is what you want:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click here</button>
<ul id="list"></ul>
<script>
var RAND_MIN = 0;
var RAND_MAX = 200;
function randomInt(low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
function myFunction() {
var answer = prompt("How many numbers must be generated randomly in a series of 200");
if (answer != null) {
var n = parseInt(answer, 10);
var list = document.getElementById("list");
for (var i = 0; i < n; ++i) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(randomInt(RAND_MIN, RAND_MAX)));
list.appendChild(li);
}
}
}
</script>
</body>
</html>
I have made a code that needs to make page-breaks after certain number of new lines or words. I have set up an array that tell me where it should cut in my element. As you can see in my jsFiddle you can see a console.log(); that shows I need to cut the text.
I would like to get help on how to create a closing </div> inserted after the specific string from my array(). I would like to have a closing </div> and a creation of a new <div>
More details about the code
// $(this)
$(this) = $('.c_84');
The HTML example
<div class=" onerow counting_1"><div class="newDiv"></div>
<div class="onefield c_6937">
<!-- This is where I want to generate the new divs -->
<table class="textarea" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td class="value"><!-- Content String --></td>
</tr>
</tbody>
</table>
</div>
</div>
Here is my code logic so far.
// The class c_6937 is the class test in my jsFiddle
// I did this just to remove extra html and focus on the problem
// Start
$(this).find('.c_6937').parent().prepend('<div class="newDiv">');
var countReqNumberOfPages = newChunk.length;
for (var key in newChunk) {
// If we find the first chunk, insert </div><div class="newDiv"> after it.
}
// End
$(this).find('.c_6937').parent().append('</div>');
Could it be possible to run a str_replace() function inside my array() and replace the current string with the exact same string plus the closing divs?
EDIT 1 : I added extra comments in the code for a better understanding of the problem and added a possible solution.
I'm not sure whether you are after something like this
<script type="text/javascript">
var wordsPerLine = 15;
var minWordsPerLine = 5;
var linesPerPage = 30;
var linesToStopAfter = [];
function checkForDot(pos,masterArray){
if(pos < 0){
return false;
}
var line = masterArray[pos];
if(line.indexOf('.') !== -1){
return line;
}
else{
return checkForDot(pos-1,masterArray);
}
}
function chunk(lines) {
var masterLines = [];
for (i = 0; i < lines.length; i++) {
var sentence = [];
var wordsList = lines[i].split(" ");
var wordCount = 0;
for (j = 0; j < wordsList.length; j++) {
if(wordCount >= wordsPerLine){
wordCount = 0;
masterLines.push(sentence.join(" "));
sentence = [];
sentence.push(wordsList[j]);
}
else{
sentence.push(wordsList[j]);
}
wordCount++;
}
masterLines.push(sentence.join(" "));
}
return masterLines
}
$(document).ready(function()
{
var html = $("#test").html();
$("#test").html('<div class="newDiv">'+html+'</div>');
var lines = chunk($("#test").text().split("\n"));
var count = 0;
for (k = 0; k < lines.length; k++) {
count++;
if(count >= linesPerPage){
count = 0;
linesToStopAfter.push(checkForDot(k,lines));
}
}
for(j=0; j<linesToStopAfter.length;j++)
{
toreplace = $("#test").html().replace(linesToStopAfter[j], linesToStopAfter[j]+"</div><div class='newDiv'>");
$("#test").html(toreplace)
}
cleanedhtml = $("#test").html().replace(/<\s*div[^>]*><\s*\/\s*div>/g,"");
$("#test").html(cleanedhtml)
});
</script>
I want to display the content in my div but the code won't work. Please show me how to do it.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for (i = 0; i < 11; i++) {
var disp = "the number is " + i;
console.log(disp);
}
disp = document.getElementById("display").innerHTML;
</script>
</body>
</html>
How can I get the loop to display my variable in my selected div? Which part of my code is wrong? please help.
Tehre are multiple problems
<p id="display"></p>
<script>
var i;
//initialize the value
var disp = '';
for (i = 0; i < 11; i++) {
//concatenate the value of disp so that new value will be added to the previous content other wise the values will be overwritten
disp += "the number is " + i;
console.log(disp);
}
//assign value of disp to the elemet innerHTML
document.getElementById("display").innerHTML = disp;
</script>
Set the innerHTML inside the for loop.
for (var i = 0; i < 11; i++) {
var disp = "the number is " + i;
document.getElementById("display").innerHTML = disp;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
IF you want to display all the content at once
var disp = ''; // Assign empty string
for (var i = 0; i < 11; i++) {
disp += " the number is " + i; // Concat message
}
document.getElementById("display").innerHTML = disp; // Add into html
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because you never write anything to your HTML page. You just display it in your console. And later you assign the HTML content of the #display element to the variable disp, which doesn't make any sense:
disp = document.getElementById("display").innerHTML;
This is how it will work
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
// This just writes to the javascript console
console.log(disp);
// This writes in the #display element on your page
document.getElementById("display").innerHTML += disp + '<br>';
}
</script>
</body>
</html>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
console.log(disp);
}
document.getElementById("display").innerHTML = disp;
Something like this should be fine
function createDivs(){
var pContainer = document.getElementById("display");
var i;
for(i = 0; i < 11; i++){
var message = "the number is " + i;
console.log(message);
var element = document.createElement("div");
element.innerHTML = message;
pContainer.appendChild(element);
}
disp = document.getElementById("display").innerHTML;
};
createDivs();