How to save inputbox value in array with Javascript - 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;
}

Related

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

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.

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>

adding inputs in for loop

I have code like that https://jsfiddle.net/Lcfnxxtv/ and i'd like to labels look like that eg.
Number of children
ages 5 - 18"
I want it in two separate lines and NOT all in one line(of course, if it's possible) 'Number of children ages 5 - 18' but i don't know how to do this in my code.
jQuery(document).ready(function() {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = jQuery("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = "</div>";
var html2 = "";
for (i = 0; i < size; i++) {
array2 = array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for (j = 0; j < size; j++) {
if (array_dla[j] == str1) {
if (jQuery.inArray(str1w, array_licz) == -1) {
array_licz[j] = str1w;
}
}
if (array_dla[j] == str2) {
if (jQuery.inArray(str2w, array_licz) == -1) {
array_licz[j] = str2w;
}
}
}
var size2 = array_licz.length;
for (k = 0; k < size2; k++) {
html += ' <label for="field[' + k + ']">' + array_licz[k] + ' ages ' + array_wie[k] + ' </label> ';
}
for (l = 0; l < size2; l++) {
html2 += '<input type="text" id="field' + l + '" value=""></input> ';
}
html += '</br>';
html += html2;
html += '</div>';
jQuery("#addon").append(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon"></div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
Please help
You have invalid tags. Input is a void element and does not needs a closing </input> tag.
<br>, <br/> are valid. </br> is not.
You have one useless for(l=0; l<size2; l++){
Use only the first k one.
Than in CSS set your label to display: block;
jQuery(function( $ ) {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = $("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = ""; // </div> ?? You mean Start of a <div>. BTW you have <label> already so ""
// html2 why??
for (i = 0; i < size; i++) {
array2 = array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for (j = 0; j < size; j++) {
if (array_dla[j] == str1) {
if ($.inArray(str1w, array_licz) == -1) {
array_licz[j] = str1w;
}
}
if (array_dla[j] == str2) {
if ($.inArray(str2w, array_licz) == -1) {
array_licz[j] = str2w;
}
}
}
var size2 = array_licz.length;
// Why loop twice size2. Loop once
for (k = 0; k < size2; k++) {
html += '<label for="field[' + k + ']">' +
array_licz[k] + '<br>ages ' + array_wie[k] +
'<br><input type="text" id="field' + k + '" value="">'+
' </label>';
}
$("#addon").append(html);
});
label{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon"></div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
The other part of your code can be also improved, but I have no idea what you're after with all those arrays...
$(document).ready(function() {
var array1 = [];
var array2 = [];
var array_typ = [];
var array_dla = [];
var array_wie = [];
var array_cen = [];
var array_licz = [];
var str = $("#all_str").val();
array1 = str.split('#');
var size = array1.length;
var str1 = "Tax A - child";
var str2 = "Tax A - elder";
var str1w = "Number of children";
var str2w = "Number of elders";
var html = "</div>";
var html2 = [];
var html3 = [];
for(i=0; i<size; i++){
array2= array1[i].split('#');
array_typ[i] = array2[0];
array_dla[i] = array2[1];
array_wie[i] = array2[2];
array_cen[i] = array2[3];
}
for(j=0; j<size; j++){
if(array_dla[j]==str1){
if($.inArray(str1w, array_licz) == -1){
array_licz[j]=str1w;
}
}
if(array_dla[j]==str2){
if($.inArray(str2w, array_licz) == -1){
array_licz[j]=str2w;
}
}
}
var size2 = array_licz.length;
for(k=0; k<size2; k++){
html3[k]='<label for="field['+ k +']">'+array_licz[k]+' ages <br>' +array_wie[k] +' </label> <br>';
}
for(l=0; l<size2; l++){
html2[l]='<input type="text" id="field'+l+'" value=""</input> <br></br>';
}
for(var j=0;j<size2;j++){
html += html3[j]+html2[j];
}
//html+='</br>';
//html+=html2;
html+='</div>';
$("#addon").append(html);
});
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addon">
</div>
<input type="hidden" id="all_str" value="XYZ#Tax A - elder#65-99#1#XYZ#Tax A - child#5-18#2#">
Your problem was the way you put the strings together. An easy solution is to use arrays and in the end you can manipulate them more easily

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');
}

Why the script is not running on all input elements?

I am using this script to hide the default value of input elements on my page:
<script>
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text
window.onload = formDefaultValues;
function formDefaultValues() {
var fields = getElementsByClassName(document, "input", "default-value");
if (!fields) {
return;
}
var default_values = new Array();
for (var i = 0; i < fields.length; i++) {
fields[i].style.color = inactive_color;
if (!default_values[fields[i].id]) {
default_values[fields[i].id] = fields[i].value;
}
fields[i].onfocus = function() {
if (this.value == default_values[this.id]) {
this.value = '';
this.style.color = active_color;
}
this.onblur = function() {
if (this.value == '') {
this.style.color = inactive_color;
this.value = default_values[this.id];
}
}
}
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
I use this code to loop on input elements that have the class "default-value" and fire the action on them. It's really working on some elements but not others? What might be going wrong?
Thanks in advance
This worked for me..
<html>
<script>
function ViewAllElements() {
var fe = document.forms['myForm'].elements;
alert(fe.length);
for(var i = 0; i < fe.length; i++)
{
alert(fe[i].value);
}
var ebc = getElementsByClassName(document, "input", "fieldA");
alert(ebc.length);
for(var j = 0; j < ebc.length; j++)
{
alert(ebc[j].value);
}
}
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i = 0; i < arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements);
}
</script>
<body>
<form id="myForm" name="myForm">
<input class="fieldA" id="field1" name="field1" value="field1value">
<input class="fieldA" id="field2" name="field2" value="field2value">
<input class="fieldA" id="field3" name="field3" value="field3value">
<input class="fieldB" id="field4" name="field4" value="field4value">
<input class="fieldB" id="field5" name="field5" value="field5value">
<input class="fieldB" id="field6" name="field6" value="field6value">
<input type="button" onClick="ViewAllElements();" value="View">
</form>
</body>
</html>

Categories