What's a good way to refactor my bloated code? - javascript

I made a simple D&D dice roll application for practice and noticed there is a lot of repetitive code. I can't find a good way to refactor it myself though. Any tips are appreciated. Fair warning, I'm a noob so I already know it's probably got more problems than I'm aware of. Feel free to really let me have it.
https://jsfiddle.net/sakonexus/nd82qjec/
function calcRoll(e) {
let die = e.target.previousElementSibling.name;
let rolls = e.target.previousElementSibling.value;
let topRow = {};
let bottomRow = {};
let randomRoll = 0;
if (rolls == '') {
rolls = 0;
}
if (die.includes("d4")) {
topRow = document.getElementById("d4-roll-results").insertRow(0);
bottomRow = document.getElementById("d4-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 4) + 1;
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
} else if (die.includes("d6")) {
topRow = document.getElementById("d6-roll-results").insertRow(0);
bottomRow = document.getElementById("d6-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 6) + 1;
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
} else if (die.includes("d8")) {
topRow = document.getElementById("d8-roll-results").insertRow(0);
bottomRow = document.getElementById("d8-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 8) + 1;
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
} else if (die.includes("d10")) {
topRow = document.getElementById("d10-roll-results").insertRow(0);
bottomRow = document.getElementById("d10-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 10);
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
} else if (die.includes("d12")) {
topRow = document.getElementById("d12-roll-results").insertRow(0);
bottomRow = document.getElementById("d12-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 12) + 1;
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
} else if (die.includes("d20")) {
topRow = document.getElementById("d20-roll-results").insertRow(0);
bottomRow = document.getElementById("d20-roll-results").insertRow(1);
topRow.insertCell(0).innerHTML = "Roll Count";
bottomRow.insertCell(0).innerHTML = "Roll Result";
for(i = 0; i < rolls; i++) {
topRow.insertCell(i + 1).innerHTML = i + 1;
}
for(j = 0; j < rolls; j++) {
randomRoll = Math.floor(Math.random() * 20) + 1;
bottomRow.insertCell(j + 1).innerHTML = randomRoll;
}
}
}

To start with, you should avoid inline handlers, they have way too many problems to be worth using. Attach listeners properly using JavaScript with addEventListener instead.
On the click of a button, navigate to its parent form or div to identify the type of dice. Then, from the parent div, navigate to the table child of the div and populate it:
document.querySelector('#dice').addEventListener('click', (e) => {
if (!e.target.matches('button')) {
return;
}
e.preventDefault();
const { target } = e;
const div = target.closest('div');
const dieType = div.dataset.dieType;
const numDice = target.previousElementSibling.value;
const table = div.querySelector('table');
table.innerHTML += `
<tr>
<td>Roll Count</td>
${Array.from({ length: numDice }, (_, i) => `<td>${i + 1}</td>`).join('')}
</tr>
<tr>
<td>Roll Result</td>
${Array.from({ length: numDice }, () => `<td>${Math.floor(Math.random() * dieType) + 1}</td>`).join('')}
</tr>
`;
});
#dice table {
border-collapse: collapse;
}
#dice td {
border: 1px solid black;
padding: 4px;
}
#dice div {
padding: 10px 0 0;
}
<div>
<h1>Select the number of rolls for each dice</h1>
<div id="dice">
<div data-die-type="4">
<form>
<label><span>D4  </span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
<hr />
<div data-die-type="6">
<form>
<label><span>D6  </span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
<hr />
<div data-die-type="8">
<form>
<label><span>D8  </span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
<hr />
<div data-die-type="10">
<form>
<label><span>D10</span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
<hr />
<div data-die-type="12">
<form>
<label><span>D12</span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
<hr />
<div data-die-type="20">
<form>
<label><span>D20</span><input type="number" min="0" max="10"><button>Confirm</button></label>
</form>
<div><table></table></div>
</div>
</div>
</div>
See how your HTML can be made dramatically more DRY as well - there's no need for all those different IDs and attributes.

Related

3D array and populate each cell in the array with the product of the indexes

I was learning javascript right now and I came across this question:
Sample Question
What i want to do is takes 3 number as input and generate a 3d array based on the input. Populate each cell in the array with the product of the indexes.
I can't figure it out. Appreciate your help
Here's an approach
function create3DArray (a, b, c) {
const matrix = [];
for (let i = 0; i < a; i++) {
matrix[i] = [];
for (let j = 0; j < b; j++) {
matrix[i][j] = [];
for (let k = 0; k < c; k++) {
matrix[i][j][k] = i * j * k;
}
}
}
return matrix;
}
console.log(create3DArray(2, 2, 2));
I've managed to create another way for this question:
// Variables
var array;
var input1;
var input2;
var input3;
// To understand how works it
/*
array[0][0][0] = "0,0,0"
array[0][0][1] = "0,0,0"
array[0][1][0] = "0,0,0"
array[0][1][1] = "0,0,0"
array[1][0][0] = "0,0,0"
array[1][0][1] = "0,0,0"
array[1][1][0] = "0,0,0"
array[1][1][1] = "0,0,0"
*/
function createArray() {
array = new Array(input1);
for (let x = 0; x < input1; x++) {
array[x] = new Array(input2);
for (let y = 0; y < input2; y++) {
array[x][y] = new Array(input3);
}
}
}
function putArrayProductValues() {
for (let x = 0; x < input1; x++) {
for (let y = 0; y < input2; y++) {
for (let z = 0; z < input3; z++) {
array[x][y][z] = x * y * z;
}
}
}
}
function viewArrayForm() {
let string = "[";
for (let x = 0; x < input1; x++) {
string += "[";
for (let y = 0; y < input2; y++) {
string += "[";
for (let z = 0; z < input3; z++) {
string += array[x][y][z];
if (z != input3 - 1) {
string += ",";
}
}
string += "]";
}
string += "]";
}
return string;
}
function execute() {
input1 = document.getElementById("input1").value;
input2 = document.getElementById("input2").value;
input3 = document.getElementById("input3").value;
createArray();
putArrayProductValues();
document.getElementById("output").innerHTML = viewArrayForm();
}
// To understand
function putArrayValues() {
for (let x = 0; x < input1; x++) {
for (let y = 0; y < input2; y++) {
for (let z = 0; z < input3; z++) {
array[x][y][z] = x.toString() + "," + y.toString() + "," + z.toString();
}
}
}
}
function showArray() {
for (let x = 0; x < input1; x++) {
for (let y = 0; y < input2; y++) {
for (let z = 0; z < input3; z++) {
console.log(array[x][y][z]);
}
}
}
}
<div class="row" style="padding: 5% 5%">
<div class="col-sm-12">
<label class="form-label">Input 1: </label>
<input id="input1" type="number" min="0" class="form-control">
</div>
<div class="col-sm-12">
<label class="form-label">Input 2: </label>
<input id="input2" type="number" min="0" class="form-control">
</div>
<div class="col-sm-12">
<label class="form-label">Input 3: </label>
<input id="input3" type="number" min="0" class="form-control">
</div>
<div class="col-sm-12" style="margin-top: 1%;">
<button type="submit" class="btn btn-primary" onclick="execute()">Submit</button>
</div>
<div class="col-sm-12" style="margin-top: 5%;">
<label class="form-label">Output: </label>
<h3 id="output"></h3>
</div>
</div>

HTML Div Element turns to null when I'm accessing it a 2nd time?

Here are the relevant bits of the client-side code:
function simpsonsShow(forest) {
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2); // simpsonsIndex is a function not shown here
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML =
document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
forest = forestGenerate(content);
simpsonsShow(forest);
});
document.getElementById("sim").appendChild(button);
});
});
When that simpsonsShow function is ran a second time, all of a sudden document.getElementById("simpsons") becomes null even though upon first try, it's a proper HTML Div Element.
Here are the relevant parts of the HTML:
<head>
<script src="sim.js"></script>
</head>
<body>
<div id="content">
<div id="intro">
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
</div><!--close id="content"-->
</body>
</html>
I've added the code snippet: The website works by pressing generate, then continually pressing generate. The error pops up once you press generate a 2nd time
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function () {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts, [emoji]: (counts[emoji] || 0) + 1 }),
{}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
alert(document.getElementById("simpsons"));
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function () {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function () {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
<!doctype html>
<html>
<head>
<title>FOREST SIMULATOR</title>
<script src="sim.js"></script>
<link rel="stylesheet" href="base.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet" >
</head>
<link href="https://fonts.googleapis.com/css?family=Lato|Playfair+Display" rel="stylesheet">
<body>
<div id="content">
<h1>FOREST SIMULATOR</h1>
<style>
.hidden{
display:none;
}
</style>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div><!--close id="content"-->
</body>
</html>
#simpsons is a child of #sim. The problem is in this code here:
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 0; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
It effectively removes all div children of #sim which don't have a pinned attribute. Try removing only divs after the first index, thereby keeping #simpsons (which is the first div inside #sim):
for (let i = 1; i < curr.length; i++) {
function forestGenerate(content) {
const forest = [];
if (content.length === 0) {
const possible = ["", "🌲", "🌳", "🌴", "🌵", "🌶", "🌷", "🌸", "🌹", "🌺", "🌻", "🌼", "🌽", "🌾", "🌿", "🍀", "🍁", "🍂", "🍃"];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
} else {
const possible = [...content, ""];
for (let i = 0; i < 8; i++) {
let text = '';
for (let i = 0; i < 8; i++) {
text += possible[Math.floor(Math.random() * possible.length)];
}
forest.push(text);
}
}
for (let i = 0; i < forest.length; i++) {
let row = document.createElement("div");
let newContent = document.createTextNode(forest[i]);
row.appendChild(newContent);
row.addEventListener("click", function() {
row.style.backgroundColor = "grey";
row.setAttribute("pinned", "yes");
});
document.getElementById("sim").appendChild(row);
}
return forest;
}
function simpsonsShow(forest) {
const simpsonsIndex = forest =>
1 - Object.entries(
[...forest.join("")].reduce(
(counts, emoji) => ({ ...counts,
[emoji]: (counts[emoji] || 0) + 1
}), {}
)
).reduce(([top, bottom], [species, count]) => [top + (count * (count - 1)), bottom + count], [0, 0])
.reduce((sumLilN, bigN) => sumLilN / (bigN * (bigN - 1)))
var ind = simpsonsIndex(forest).toFixed(2);
document.getElementById("simpsons").innerHTML = "";
document.getElementById("simpsons").innerHTML = document.getElementById("simpsons").innerHTML + ind;
}
document.addEventListener("DOMContentLoaded", function() {
let element = document.getElementById("sim");
element.classList.add("hidden");
let element1 = document.getElementById("pushtray");
element1.classList.add("hidden");
document.querySelector("div#intro button").addEventListener("click", function clicked() {
document.getElementById("intro").style.display = "none";
document.getElementById("sim").style.display = "block";
document.getElementById("simpsons").style.display = "block";
let content = document.getElementById("inputForest").value;
let forest = forestGenerate(content);
const ind = simpsonsShow(forest);
if (ind <= .7) {
let over = document.createElement("div");
let newContent = document.createTextNode("WARNING: Simpson's Index Dropped To" + simpsonsIndex);
over.appendChild(newContent);
document.getElementById("pushtray").appendChild(over);
document.getElementById("pushtray").style.zIndex = "100";
document.getElementById("pushtray").style.right = "50px";
document.getElementById("pushtray").style.position = "fixed";
document.getElementById("pushtray").style.display = "block";
}
let button = document.createElement("button");
button.appendChild(document.createTextNode("generate"));
button.addEventListener("click", function() {
const curr = document.getElementById("sim").querySelectorAll("div");
for (let i = 1; i < curr.length; i++) {
if (!curr[i].hasAttribute("pinned")) {
document.getElementById("sim").removeChild(curr[i]);
}
}
document.getElementById("sim").removeChild(button);
forest = forestGenerate(content);
simpsonsShow(forest);
document.getElementById("sim").appendChild(button);
});
document.getElementById("sim").appendChild(button);
});
});
.hidden {
display: none;
}
<div id="content">
<h1>FOREST SIMULATOR</h1>
<div id="intro">
starting forest (leave empty to randomize):
<br />
<textarea id="inputForest" name="inputForest" cols="16" rows="8"></textarea>
<br />
<button>generate</button>
</div>
<div id="sim" class="hidden">
<h2>the current Simpson's Index is:
</h2>
<div id="simpsons">
</div>
</div>
<div id="pushtray" class="overlay">
</div>
</div>

Removing Target _blank in JavaScript

I want to remove the target="_blank" in the given code and also, show me how to add unordered list or ordered list.
Random Post example: Check the bottom of the page
<div class='kotakleft'>
<div class='boxleft'>
<ul id='random-posts' />
<script>
var homePage = "http://www.example.com/",
numPosts = 7;
function randomPosts(a) {
if (document.getElementById("random-posts")) {
var e = shuffleArray(a.feed.entry), title, link, img, content = "", ct = document.getElementById("random-posts");
for (var i = 0; i < numPosts; i++) {
for (var j = 0; j < numPosts; j++) {
if (e[i].link[j].rel == "alternate") {
link = e[i].link[j].href;
break
}
}
var title = e[i].title.$t;
content += '<div class="random-posts"><li>' + title + '</li></div>'
}
ct.innerHTML = content
}
}
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp
}
return arr
}
var random_post = document.createElement('script');
random_post.src = homePage + '/feeds/posts/summary?alt=json-in-script&orderby=published&max-results=999&callback=randomPosts';
document.getElementsByTagName('head')[0].appendChild(random_post);
</script>
</div>
</div>
How can I do this?
It's very simple, you just need to change a few things:
<div class='boxleft'>
<ul id='random-posts' />
<script>
var homePage = "http://www.example.com/",
numPosts = 7;
function randomPosts(a) {
if (document.getElementById("random-posts")) {
var e = shuffleArray(a.feed.entry), title, link, img, content = "", ct = document.getElementById("random-posts");
content = '<ul>';
for (var i = 0; i < numPosts; i++) {
for (var j = 0; j < numPosts; j++) {
if (e[i].link[j].rel == "alternate") {
link = e[i].link[j].href;
break
}
}
var title = e[i].title.$t;
content += '<li><div class="random-posts">' + title + '</div></li>'
}
content = '</ul>';
ct.innerHTML = content
}
}
function shuffleArray(arr) {
var i = arr.length, j, temp;
if (i === 0) return false;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp
}
return arr
}
var random_post = document.createElement('script');
random_post.src = homePage + '/feeds/posts/summary?alt=json-in-script&orderby=published&max-results=999&callback=randomPosts';
document.getElementsByTagName('head')[0].appendChild(random_post);
</script>
</div>
</div>

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

How to save inputbox value in array with Javascript

I'm new to Javascript.
I want to store input boxes value in array, but I have problem with this.
I use below code; please guide me:
<form>
<input type="text" id="NumElement" />
<button onclick="return Give()" />Give</button>
<div id="inputs"></div>
<p>Block Number: <input type="text" id="NoArrey" /></p>
<button onclick="return Show()" />Show</button>
<input type="text" id="Result" />
</form>
<script>
function Give() {
var Num = document.getElementById('NumElement').value;
var i = 0;
for (i = 0; i < Num; i++) {
var m = i + 1;
inputs.innerHTML = inputs.innerHTML +"<br><input type='text' id='v" + m + "'>";
};
inputs.innerHTML = inputs.innerHTML +"<br><button id='Save' onclick='return Save()'>Save</button>";
return false;
}
function Save() {
var MyArray = new Array();
var j = 0;
for (j = 0; j < Num; j++) {
var InputValue = document.getElementById('v' + j);
MyArray.push(InputValue.value);
}
function Show() {
var no = document.getElementById('NoArrey').value;
document.getElementById("Result").value = (MyArray[no]);
return false;
}
</script>
Maybe you did a typo but in the save() function you don't declare var num. You are declaring num in the give() function.
this should work.
EDIT:
function Give() {
var Num = document.getElementById('NumElement').value;
var i = 0;
for (i = 0; i < Num; i++) {
var m = i + 1;
inputs.innerHTML = inputs.innerHTML +"<br><input type='text' id='v" + m + "'>";
};
inputs.innerHTML = inputs.innerHTML +"<br><button id='Save' onclick='return Save()'>Save</button>";
return false;
}
function Save() {
var Num = document.getElementById('NumElement').value;
var MyArray = new Array();
var j = 0;
for (j = 0; j < Num; j++) {
var InputValue = document.getElementById('v' + j);
MyArray.push(InputValue.value);
}
function Show() {
var no = document.getElementById('NoArrey').value;
document.getElementById("Result").value = (MyArray[no]);
return false;
}

Categories