Work with 2d array in javascript - javascript

I create 2d array with random number
<script type="text/javascript">
function matrixArray(rows, columns) {
var min = 0;
var max = 10;
var arr = new Array();
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < columns; j++) {
arr[i][j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
}
return arr;
}
</script>
Now i wont write function that create table with delete button in all rows. And function that delete row from array and redraw the table. Try like this, but not working
<script>
function createtab (arr)
{
var inpts = [], t = document.createElement('TABLE');
t.cellSpacing = 0, t.cellPadding = 5, t.border = 1;
for (var j = 0, J = arr.length; j < J; j++) {
var ro = t.insertRow(-1),
ce = ro.insertCell(-1),
inpt = document.createElement('INPUT');
inpt.type = 'button', inpt.value = 'Delete', inpt.onclick = 'rowdel(arr,'+j+')';
inpts.unshift(ce.appendChild(inpt));
for (var k = 0, K = arr[j].length; k < K; k++) { var ce = ro.insertCell(-1); ce.innerHTML = arr[j][k] }
}
var obj = document.getElementById('forTable').appendChild(t);
}
</script>
delete row on button click
<script>
function rowdel(arr, i) {
arr.splice(i, 1);
createtab(arr);
}
</script>
html body
<body>
<div id="forTable"></div>
<script>
var arr = matrixArray(6, 7);
createtab(arr);
</script>
</body>

EDITED
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var arr = matrixArray(6, 7);
createtab(arr);
});
function matrixArray(rows, columns) {
var min = 0;
var max = 10;
var arr = new Array();
for (var i = 0; i < rows; i++) {
arr[i] = new Array();
for (var j = 0; j < columns; j++) {
arr[i][j] = Math.floor(Math.random() * (max - min + 1)) + min;
}
}
return arr;
}
function createtab (arr)
{
var inpts = [], t = document.createElement('TABLE');
t.cellSpacing = 0, t.cellPadding = 5, t.border = 1;
for (var j = 0, J = arr.length; j < J; j++) {
var ro = t.insertRow(-1),
ce = ro.insertCell(-1),
inpt = document.createElement('INPUT');
inpt.type = 'button', inpt.value = 'Delete',inpt.attributes['id']=j, inpt.onclick =function() { rowdel(arr,this)};
inpts.unshift(ce.appendChild(inpt));
for (var k = 0, K = arr[j].length; k < K; k++) { var ce = ro.insertCell(-1); ce.innerHTML = arr[j][k];
//alert(j);
}
}
var obj = document.getElementById('forTable').appendChild(t);
}
function rowdel(arr,input) {
var i = input.attributes['id'];
arr.splice(i, 1);
$('#forTable').empty();
createtab(arr);
}
</script>
<body>
<div id="forTable"></div>
</body>

you don't need to redraw the table .
inpt.onclick = 'rowdel(arr,'+j+',this)';
function rowdel(arr, i, input) {
arr.splice(i, 1);
var row = input.parentNode.parentNode;
row.parentNode.removeChild(row);
}
UPDATE: onclick requires a function
inpt.attributes['id']=j;
inpt.onclick = function () {
rowdel(this);
};
function rowdel(input) {
var i = input.attributes['id'];
arr.splice(i, 1);
var row = input.parentNode.parentNode;
row.parentNode.removeChild(row);
}

you can define you del function such like that.
var dele = function rowdel(arr, i) {
return function(){
arr.splice(i, 1);
createtab(arr);
}
}
and use it as like closures as .
inpt.type = 'button', inpt.value = 'Delete', inpt.onclick = dele(arr, j);

Related

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>

Unable to Delete Cells using JavaScript: The value provided (3) is outside the range

function selectTo(cell) {
var row = cell.parent();
var cellIndex = cell.index();
var rowIndex = row.index();
var rowStart, rowEnd, cellStart, cellEnd;
if (rowIndex < startRowIndex) {
rowStart = rowIndex;
rowEnd = startRowIndex;
sessionStorage.setItem('rowStart', rowStart);
sessionStorage.setItem('rowEnd', rowEnd);
} else {
rowStart = startRowIndex;
rowEnd = rowIndex;
sessionStorage.setItem('rowStart', rowStart);
sessionStorage.setItem('rowEnd', rowEnd);
}
if (cellIndex < startCellIndex) {
cellStart = cellIndex;
cellEnd = startCellIndex;
sessionStorage.setItem('cellStart', cellStart);
sessionStorage.setItem('cellEnd', cellEnd);
} else {
cellStart = startCellIndex;
cellEnd = cellIndex;
sessionStorage.setItem('cellStart', cellStart);
sessionStorage.setItem('cellEnd', cellEnd);
}
for (var i = rowStart; i <= rowEnd; i++) {
var TableID = sessionStorage.getItem("TableID");
var table6 = document.getElementById(TableID);
var row6 = table6.getElementsByTagName('tr')[i];
var rowCells = row6.getElementsByTagName('td');
for (var j = cellStart; j <= cellEnd; j++) {
rowCells[j].className = "hover";
}
}
}
var TableID = sessionStorage.getItem("TableID");
var cellStart = sessionStorage.getItem("cellStart");
var cellEnd = sessionStorage.getItem("cellEnd");
var rowStart = sessionStorage.getItem("rowStart");
var rowEnd = sessionStorage.getItem("rowEnd");
for (var i = rowStart; i <= rowEnd; i++) {
var myTable = document.getElementById(TableID);
var row10 = myTable.getElementsByTagName('tr')[i];
var rowCells = row10.getElementsByTagName('td');
for (var j = cellStart; j < cellEnd; j++) {
if (j === cellStart && i === rowStart)
continue;
//rowCells[j].style.display = "none";
myTable.rows[i].deleteCell(j);
}
}
When I delete cells, use a different method table.row[i].deleteCell(j); or removechild I get out of range error.
mesage:
Uncaught DOMException: Failed to execute 'deleteCell' on
'HTMLTableRowElement': The value provided (3) is outside the range [0,
3).
at init.callback
I find solution:
var listHover = document.querySelectorAll('.hover');
for (var i = 0; i < listHover.length; i++) {
if (i > 0) {
listHover[i].style.display = 'none';
}
}

js Page Freezing on from .length?

This function is freezing my page.
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
}
However, when I remove this it runs just fine.
modeArr.length = array.length;
modeCounter.length = array.length;
Here is all of my code:
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br><p>
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "mean"></p>
<p id = "median"></p>
<p id = "count"></p>
<p id = "summation"></p>
<p id = "mode"></p>
<p id = "variance"></p>
<p id = "sd"></p>
<script type = "text/javascript">
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var medianOutput = document.getElementById('median');
var modeOutput = document.getElementById('mode');
var countOutput = document.getElementById('count');
var summationOutput = document.getElementById('summation');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMean(arrayOfLines, sum);
findMedian(arrayOfLines);
findMode(arrayOfLines);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
findVariance(arrayOfLines);
}
function findSum (array)
{
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++)
{
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
summationOutput.innerHTML = "Sum: " + JSON.stringify(sum);
return sum;
}
function findMode (array)
{
var modeArr = [];
var modeCounter = [];
modeArr.length = array.length;
modeCounter.length = array.length;
for (var a = 0; a < array.length; a++)
{
for (var b = 0; b < modeArr.length; b++)
{
if (modeArr[a] == modeArr[b])
{
modeCounter[a]++;
}
if (a == 0)
{
b--;
}
}
modeArr[a] = array[a];
}
modeOutput.innerHTML = "Mode: ";
}
function findMean (array, sum)
{
mean = sum/array.length;
meanOutput.innerHTML = "Mean: " + mean.toPrecision(2);
}
function findMedian (array)
{
for(var i=0; i < array.length; i++)
{
array[i] = +array[i];
}
var sortedArrayOfLines = array.sort(function(a, b){return a - b});
if (array.length % 2 == 1)
{
median = sortedArrayOfLines[((array.length - 1)/2)]
}
else
{
median = (sortedArrayOfLines[array.length/2] + sortedArrayOfLines[(array.length/2)+1])/2
}
medianOutput.innerHTML = "Median: " + median;
}
function findVariance (array)
{
var mean = mean(array);
return mean(array.map(function(num)
{
varianceOutput.innerHTML = Math.pow(num - mean, 2);
}));
}
function findStandardDeviation (array)
{
medianOutput.innerHTML = Math.sqrt(variance(array));
}
</script>
</body>
</html>
So the issue isn't the length it's a infinite loop.
The problem is this bit of code
if (a == 0)
{
b--;
}
This is inside the following loop with b as the iterator. See below.
for (var b = 0; b < modeArr.length; b++)
a is set to zero by the outer loop. Thus a==0 is always true inside the inner loop. b will never increase only decrease. Thus this is a infinite loop because b will never be greater than modeArr.length.
So I would consider revising the function, below is a example of a possible candidate for a mode function:
Get the element with the highest occurrence in an array

Keep the clicked objects in an array in javascript

I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}

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

Categories