minesweeper getAttribute of null error - javascript

Recently been creating minesweeper and came across a "Cannot read property 'getAttribute' of undefined" error on lines 19, 39, and 62 of my javascript code. I added the HTML to show where the javascript code is getting the variables from.
document.getElementById("begin").addEventListener("click", startGame);
let vertical;
let horizontal;
let DIFFICULTY;
let GG = false;
document.body.addEventListener('contextmenu', function(cm){e.preventDefault();});
function Winner(){
let ckCt = document.querySelectorAll('[clicked]').length;
let mCt = document.querySelectorAll('[mine]').length;
let cCt = horizontal * vertical;
if(cCt == ckCt + mCt){
GG = true;
return true;
}
return false;
}
function acrossTheBlock(cell){
let x = parseInt(cell.getAttribute('x'));
let y = parseInt(cell.getAttribute('y'));
//(x-1, y-1) (x, y-1) (x+1, y-1)
//(x-1, y) (x, y) (x+1, y)
//(x-1, y+1) (x, y+1) (x+1, y+1)
let nw = document.getElementById((x-1) + "_" + (y-1));
let n = document.getElementById((x) + "_" + (y-1));
let ne = document.getElementById((x+1) + "_" + (y-1));
let w = document.getElementById((x-1) + "_" + (y));
let e = document.getElementById((x+1) + "_" + (y));
let sw = document.getElementById((x-1) + "_" + (y+1));
let s = document.getElementById((x) + "_" + (y+1));
let se = document.getElementById((x+1) + "_" + (y+1));
return [nw, n, ne, w, e, sw, s, se];
}
function amt(count){
let z = 0;
let nextDoor = acrossTheBlock();
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
return count;
}
function findTheMine(e){
if(isNewGame){ this.removeAttribute("mine"); }
isNewGame = false;
if(this.classList.contains('flag')) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.hasAttribute("mine")){
//You lose!
isGameOver = true;
let bombs = document.querySelectorAll("[mine]");
for(var i = 0; i < bombs.length; i++){
bombs[i].className = "boom";
}
return;
}
this.setAttribute('clicked', true);
let BOOM = amt(this);
if(BOOM){
this.innerHTML = BOOM;
this.className = "c" + BOOM;
} else {
let nextDoor = acrossTheBlock(block);
for(var n = 0; n < nextDoor.length; n++){
if(nextDoor[n] && nextDoor[n].hasAttribute("mine")){
count++
}
}
}
isWin();
}
function IThinkIFoundTheMine(yay){
yay.preventDefault();
if(GG) { return; }
if(this.hasAttribute('clicked')) { return; }
if(this.classList.contains('flag')){
this.classList.remove('flag');
} else {
this.className = 'flag';
}
}
function getDifficulty(){
let radios = document.getElementsByName("difficulty");
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
return parseFloat(radios[i].value);
}
}
}
function startGame(){
vertical = parseInt(document.getElementById("vertical").value);
horizontal = parseInt(document.getElementById("horizontal").value);
DIFFICULTY = getDifficulty();
isNewGame = true;
isGameOver = false;
//clear out old gameboard (this allows for a new game.)
document.getElementById("minefield").innerHTML = "";
//dynamically build table.
var table = document.createElement("table");
document.getElementById("minefield").appendChild(table);
for(var r = 0; r < horizontal; r++){
var mineRows = document.createElement("tr");
table.appendChild(mineRows);
for(var c = 0; c < vertical; c++){
var textbox = document.createElement("td");
textbox.addEventListener("click", findTheMine);
textbox.addEventListener("contextmenu", IThinkIFoundTheMine);
textbox.setAttribute("id", c + "_" + r);
textbox.setAttribute("x", c);
textbox.setAttribute("y", r);
if(Math.random() < DIFFICULTY){
textbox.setAttribute("mine", true);
}
mineRows.appendChild(textbox);
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="minesweeper.css"/>
<title>Explosion</title>
</head>
<body>
<input id="horizontal" type="number" value="10">
<input id="vertical" type="number" value="10">
<input name="difficulty" value=".1" type="radio">Easy
<input name="difficulty" value=".2" type="radio" checked="true">Medium
<input name="difficulty" value=".3" type="radio">Hard
<input name="difficulty" value=".8" type="radio">Impossible
<button id="begin">Good Luck</button>
<div id="minefield"></div>
<script type="text/javascript" src="minesweeper.js"></script>
</body>
</html>
How can I fix this error?

On line 39 the script calls acrossTheBlock() without passing the argument (cell) needed to do cell.getAttribute() on the first two lines under that function.

Related

How do I display a function using setTimeout in JavaScript?

I have made a quiz with JavaScript and want that when the timer is up, it should not let you attempt the quiz anymore and go to the last page which displays the score. The score is displayed by calling displayResult. I have one HTML file and one JS file. When I use setTimeout, even after the time is up, it doesn’t show the score. I think the function doesn’t get called. I have tried using setInterval instead of setTimeout but still it doesn't work. Can someone tell me what I am doing wrong?
Whole code here.
//timer code in quiz.js
const startingMinutes = 1
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
if (time == 0) {
clearInterval(vri);
}
setTimeout(displayResult, 1000);
}
The function gets called you can easily check this by inserting a console.log() inside the function.
When you would like to display the results on the same page then first clear the body and append your new created element on the body.
There is still a bug that your selected elements will always be empty but I just answer your question here "How you display it."
For debugging purposes I set the timer to 6 seconds instead of 60.
(function() {
var allQuestions = [{
question: "The tree sends downroots from its branches to the soil is know as:",
options: ["Oak", "Pine", "Banyan", "Palm"],
answer: 2
}, {
question: "Electric bulb filament is made of",
options: ["Copper", "Aluminum", "lead", "Tungsten"],
answer: 3
}, {
question: "Non Metal that remains liquid at room temprature is",
options: ["Phophorous", "Bromine", "Clorine", "Helium"],
answer: 1
}, {
question: "Which of the following is used in Pencils ?",
options: ["Graphite", "Silicon", "Charcoal", "Phosphorous"],
answer: 0
}, {
question: "Chemical formula of water ?",
options: ["NaA1O2", "H2O", "Al2O3", "CaSiO3"],
answer: 1
}, {
question: "The gas filled in electric bulb is ?",
options: ["Nitrogen", "Hydrogen", "Carbon Dioxide", "Oxygen"],
answer: 0
}, {
question: "Whashing soda is the comman name for",
options: ["Sodium Carbonate", "Calcium Bicarbonate", "Sodium Bicarbonate", "Calcium Carbonate"],
answer: 0
}, {
question: "Which gas is not known as green house gas ?",
options: ["Methane", "Nitrous oxide", "Carbon Dioxide", "Hydrogen"],
answer: 3
}, {
question: "The hardest substance availabe on earth is",
options: ["Gold", "Iron", "Diamond", "Platinum"],
answer: 2
}, {
question: "Used as a lubricant",
options: ["Graphite", "Silica", "Iron Oxide", "Diamond"],
answer: 0
}];
var quesCounter = 0;
var selectOptions = [];
var quizSpace = $('#quiz');
nextQuestion();
$('#next').click(function() {
chooseOption();
if (isNaN(selectOptions[quesCounter])) {
alert('Please select an option !');
} else {
quesCounter += 5;
nextQuestion();
}
});
$('#prev').click(function() {
chooseOption();
quesCounter -= 5;
nextQuestion();
});
function createElement(index) {
var element = $('<div>', {
id: 'question'
});
var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>');
element.append(header);
var question = $('<p>').append(allQuestions[index].question);
element.append(question);
var radio = radioButtons(index);
element.append(radio);
var question1 = $('<p>').append(allQuestions[index + 1].question);
element.append(question1);
var radio1 = radioButtons1(index + 1);
element.append(radio1);
var question2 = $('<p>').append(allQuestions[index + 2].question);
element.append(question2);
var radio2 = radioButtons2(index + 2);
element.append(radio2);
var question3 = $('<p>').append(allQuestions[index + 3].question);
element.append(question3);
var radio3 = radioButtons3(index + 3);
element.append(radio3);
var question4 = $('<p>').append(allQuestions[index + 4].question);
element.append(question4);
var radio4 = radioButtons4(index + 4);
element.append(radio4);
return element;
}
function radioButtons(index) {
var radioItems = $('<ul>');
var item;
var input = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += allQuestions[index].options[i];
item.append(input);
radioItems.append(item);
}
return radioItems;
}
function radioButtons1(index) {
var radioItems1 = $('<ul>');
var item1;
var input1 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item1 = $('<li>');
input1 = '<input type="radio" name="answer1" value=' + i + ' />';
input1 += allQuestions[index].options[i];
item1.append(input1);
radioItems1.append(item1);
}
return radioItems1;
}
function radioButtons2(index) {
var radioItems2 = $('<ul>');
var item2;
var input2 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item2 = $('<li>');
input2 = '<input type="radio" name="answer2" value=' + i + ' />';
input2 += allQuestions[index].options[i];
item2.append(input2);
radioItems2.append(item2);
}
return radioItems2;
}
function radioButtons3(index) {
var radioItems3 = $('<ul>');
var item3;
var input3 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item3 = $('<li>');
input3 = '<input type="radio" name="answer3" value=' + i + ' />';
input3 += allQuestions[index].options[i];
item3.append(input3);
radioItems3.append(item3);
}
return radioItems3;
}
function radioButtons4(index) {
var radioItems4 = $('<ul>');
var item4;
var input4 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item4 = $('<li>');
input4 = '<input type="radio" name="answer4" value=' + i + ' />';
input4 += allQuestions[index].options[i];
item4.append(input4);
radioItems4.append(item4);
}
return radioItems4;
}
function chooseOption() {
selectOptions[quesCounter] = +$('input[name="answer"]:checked').val();
selectOptions[quesCounter + 1] = +$('input[name="answer1"]:checked').val();
selectOptions[quesCounter + 2] = +$('input[name="answer2"]:checked').val();
selectOptions[quesCounter + 3] = +$('input[name="answer3"]:checked').val();
selectOptions[quesCounter + 4] = +$('input[name="answer4"]:checked').val();
}
function nextQuestion() {
quizSpace.fadeOut(function() {
$('#question').remove();
if (quesCounter < allQuestions.length) {
var nextQuestion = createElement(quesCounter);
quizSpace.append(nextQuestion).fadeIn();
if (!(isNaN(selectOptions[quesCounter, quesCounter + 1, quesCounter + 2, quesCounter + 3, quesCounter + 4]))) {
$('input[value=' + selectOptions[quesCounter] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 1] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 2] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 3] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 4] + ']').prop('checked', true);
}
if (quesCounter === 1) {
$('#prev').show();
} else if (quesCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreRslt = displayResult();
quizSpace.append(scoreRslt).fadeIn();
$('#next').hide();
$('#prev').hide();
}
});
}
const startingMinutes = 0.1;
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
console.log(time);
if (time === 0) {
clearInterval(vri);
setTimeout(displayResult, 1000);
}
}
function displayResult() {
console.log(selectOptions);
var correct = 0;
console.log(selectOptions);
for (var i = 0; i < selectOptions.length; i++) {
if (selectOptions[i] === allQuestions[i].answer) {
correct++;
}
}
document.body.innerHTML = "";
let score = document.createElement("p");
score.id = 'question';
if (correct === 0 && correct <= 5) {
let otherText = document.createTextNode("YOUR IQ SCORES LIES IN THE RANGE OF 70 and 79 WHICH IS CLASSIFIED AS BORDERLINE");
let img = document.createElement("img");
img.src = "img9b.png"
score.append(otherText)
score.append(img);
} else {
let tex = document.createTextNode("The Result is: " + correct);
score.appendChild(tex);
}
document.body.appendChild(score);
}
})();
<html>
<head>
<title>Make Quiz Website</title>
<link rel="stylesheet" href="quiz.css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Quiz Website Using JavaScript</h1>
<br/>
<div id="quiz"></div>
<p id="countdown">30:00</p>
</h1>
<div class="button" id="next">Next</div>
<div class="button" id="prev">Prev</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="quiz.js"></script>
</body>
</html>

Why aren't numbers matching? They are absurdly higher than asked

I progressed in my code, but now for some reason the asked minimum and maximum numbers aren't matching!
I tried to fix some numbers adding for loops. But I think I only made it worse.
I made it on Dcoder(Phone)
var rndList = [];
var rndList2 = [];
function GD() {
var a = document.getElementById("MinS").value;
var b = document.getElementById("MaxS").value;
var c = document.getElementById("Min").value;
var d = document.getElementById("Max").value;
var e = document.getElementById("PrzNo").value;
r = [a, b, c, d, e];
return r;
}
var input = document.getElementsByClassName("o");
for (i = 0; i < input.length; i++) {
input[i].addEventListener("change", function() {
results = GD();
var a = results[0];
var b = (results[1] + 1);
var c = results[2];
var d = (results[3] + 1);
var e = results[4];
function raffle(MinS, MaxS, Min, Max, PrzNo) {
function getRndInt(min, max) {
return (Math.round(Math.random() * (max - min)) + min);
}
for (i = 0; i < PrzNo; i++) {
rndList.push(getRndInt(MinS, MaxS));
}
for (i = 0; i < PrzNo; i++) {
rndList2.push(getRndInt(Min, Max));
}
}
raffle(a, b, c, d, e);
for (i = 0; i < rndList.length; i++) {
while (rndList[i] >= b) {
rndList[i] = Math.round(rndList[i] / 10);
}
}
for (i = 0; i < rndList2.length; i++) {
while (rndList2[i] >= d) {
rndList2[i] = Math.round(rndList2[i] / 10);
}
}
for (i = 0; i < rndList.length; i++) {
if (rndList[i] == 0) {
rndList[i] = 1;
}
}
for (i = 0; i < rndList2.length; i++) {
if (rndList2[i] == 0) {
rndList2[i] = 1;
}
}
for (i = 0; i < rndList.length; i++) {
window.alert("Serial: " + rndList[i] + " y Number: " + rndList2[i]);
}
});
};
.center {
display: block;
text-align: center;
width: 50%;
border: 1px dotted #f00;
padding: 8px;
margin: auto;
}
<form action="Raffle.html" method="post" name="frm">
<p class="center"> Minimum Serial: <input class="center o" type="number" name="MinS" id="MinS"><br> Maximum Serial: <input class="center o" type="number" name="MaxS" id="MaxS"><br> Minimum Number: <input class="center o" type="number" name="Min" Id="Min"><br> Maximum
Number: <input class="center o" type="number" name="Max" id="Max"><br> Amount of Prizes: <input class="center o" type="number" name="PrzNo" id="PrzNo"></p>
</form>
I hope you can find what's wrong. I have another question, do you know some app or web page that reorganize your code? For making it more beautiful.

How can I create a secret message app using the square code method?

I need to create a secret message app, such that a text:
"If man was meant to stay on the ground, god would have given us roots."
is normalized to:
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots"
And the normalised text forms a rectangle (​r x c​) where ​c​ is the number of columns and ​r​ is the number of rows such that ​c >= r​ and ​c - r <= 1​,
So for instance the normalized text is 54 characters long, dictating a rectangle with ​c = 8​ and ​r = 7​:
"ifmanwas"
"meanttos"
"tayonthe"
"groundgo"
"dwouldha"
"vegivenu"
"sroots "
Then the coded message is obtained by reading down the columns going left to right
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
and further split to
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau"
The resulting cypher text for a non perfect rectangle can only have a single whitespace for the last rows.
"imtgdvs"
"fearwer"
"mayoogo"
"anouuio"
"ntnnlvt"
"wttddes"
"aohghn "
"sseoau "
This what I have done so far, I could only get my normalised text, but I am doing something wrong to convert it to a rectangle and to get a cypher text out of it.
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
function wordCount() {
return message.split(" ").length;
}
if (wordCount < 2 || message.length < 50) {
error.innerHTML = "Invalid message, Input more than one word and at Least 50 characters!";
return false;
}
function normaliseMessage() {
return message.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
}
function rectangleSize() {
return Math.ceil(Math.sqrt(normaliseMessage.length));
}
function splitRegEx() {
return new RegExp(".{1," + rectangleSize + "}", "g");
}
function plaintextSegments() {
return normaliseMessage.match(splitRegEx);
}
function ciphertext() {
var columns = [],
currentLetter, currentSegment;
var i, j;
for (let i = 0; i < rectangleSize; i++) {
columns.push([]);
}
for (i = 0; i < plaintextSegments.length; i++) {
currentSegment = plaintextSegments[i];
for (j = 0; j < columns.length; j++) {
currentLetter = currentSegment[j];
columns[j].push(currentLetter);
}
}
for (i = 0; i < columns.length; i++) {
columns[i] = columns[i].join("");
}
return columns.join("");
}
function normalizeCipherText() {
return ciphertext.match(splitRegEx).join(" ");
}
text.innerHTML = plaintextSegments();
encodedChunks.innerHTML = ciphertext();
output.innerHTML = normalizeCipherText();
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks">
</p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle">
</p>
</div>
Most of your code is constructed of very short methods.
Usually I'd consider a good practice, but in this case I think it just made the code less readable.
Additionally, I have to say that the HTML part wasn't necessary in terms of solving the issue - which was clearly Javascript/algorithm related.
This is my solution, which can be modified to match your context:
const input = "If man was meant to stay on the ground, god would have given us roots.";
const normalizedInput = input.replace(/[^\w]/g, "").toLowerCase();
const length = normalizedInput.length;
const cols = Math.ceil(Math.sqrt(length));
const rows = Math.ceil(length / cols);
var cypherText = "";
for (let i = 0; i < cols; i ++) {
for (let j = i; j < normalizedInput.length; j += cols) {
cypherText += normalizedInput[j];
}
cypherText += '\n';
}
console.log(cypherText);
This is what I came up with
const output = document.querySelector('#encoded_rectangle');
const encodedChunks = document.querySelector('#encoded_chunks');
const text = document.querySelector('#normalized_text');
const string = document.querySelector('#message');
const error = document.querySelector('#alert');
const encodeMessage = () => {
let message = string.value;
var normalisedText = message.replace(/[^a-zA-Z0-9]/g, "");
var textCount = normalisedText.length;
if (textCount < 50) {
console.log("Invalid message, Input more than one word and at Least 50 characters!");
return false;
}
var higest = Math.ceil(Math.sqrt(textCount));
var lowest = Math.ceil(textCount/higest);
var rect = [];
var coded = [];
var innerObj = {};
var resulting = "";
rect = rectangleSize(higest,lowest,normalisedText);
//read text from top-down i hotago!!!
coded = readFromTopDown(rect, higest);
coded.forEach(co => {
resulting += co.trim();
});
//nwa idi sharp, nice logic
console.log("Normalized: " + normalisedText);
console.log("Count: " + textCount);
console.log(rect);
console.log(coded);
console.log("Resulting: " + resulting);
function rectangleSize(higest, lowest, normalise) {
var rect = [];
var startIndex = 0;
for(var i = 0; i < lowest; i++){
if(i !== 0)
startIndex += higest;
if(normalise.substring(startIndex, startIndex + higest).length == higest){
rect.push(normalise.substring(startIndex, startIndex + higest))
}else{
//get the remainder as spaces
var spaces = higest - normalise.substring(startIndex, startIndex + higest).length;
var textI = normalise.substring(startIndex, startIndex + higest);
var str = textI + new Array(spaces + 1).join(' ');
rect.push(str);
}
}
return rect;
}
function readFromTopDown(rect, higest) {
var coded = [];
for(var i = 0; i < higest; i++){
var textMain = "";
rect.forEach(re => {
textMain += re.substring(i, i+1);
});
coded.push(textMain);
}
return coded;
}
}
<form>
<input type="text" placeholder="Type your secret message" id="message">
<p id="alert"></p>
<button type="button" class="button" onclick="encodeMessage()">Encode message</button>
</form>
<div class="box">
<h3>Normalised Text</h3>
<p id="normalized_text"></p>
</div>
<div class="box">
<h3>Encoded Chunks</h3>
<p id="encoded_chunks"></p>
</div>
<div class="box">
<h3>Encoded Rectangle</h3>
<p id="encoded_rectangle"></p>
</div>
Try and see

User inputs information into text box which makes allows user to select multiple words and creates different Titles based on the selections

I am gaining user input from four different areas and I want to take those options and convert them to an array which will loop through and display different variations of the words selected. The problem I am having is that the array will not cycle through the variables when passed through it unless they are already pre-defined.
<!DOCTYPE html>
<html>
<head>
<title> Title Generation Module</title>
<script src="title.js" type="text/javascript"></script>
<script src="find.js" type="text/javascript"></script>
<script src="replace.js" type="text/javascript"></script>
<script src="search.js" type="text/javascript"></script>
<script src="generate.js" type="text/javascript"></script>
<!-- <script src="check.js" type="text/javascript"></script>--> <!-- Leaving for future usage not needed at this point -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="jquery-1.11.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="title.css">
</head>
<body>
<h1>Title Generation Module</h1>
<h2>Example</h2>
<p>When you type into Core Words you want to put words that cannot change such as: Logitech
</br> For Word Combinations you want to use words such as: Brand New or Power Adaptor
</br> For Swapped Words you might want to use: Gaming instead of Performance or vice versa
</br> For Synonyms you want to use words that mean the same thing such as for = 4 or at = #</p>
<h3>Core Words</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCore"/>
<button id="addCore">Insert</button>
<label for="coreContain">Select as many as you like:</label>
<select id="coreContain" name="coreContain" multiple></select>
<button id="checkCore" onclick="checkCore()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCore").click(function()
{
$("#coreContain").append('<option value="' + $("#newCore").val() + '">' + $("#newCore").val() + '</option>');
});
});
$('#coreContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var coreOptions = new Array();
$('form').submit(
function()
{
$('#coreContain > option:selected').each(
function(i)
{
coreOptions[i] = $(this).val();
});
//window.alert(coreOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs Word Combinations -->
<h3>Word Combinations</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newCombo"/>
<button id="addCombo">Insert</button>
<label for="comboContain">Select as many as you like:</label>
<select id="comboContain" name="comboContain" multiple></select>
<button id="checkCombo" onclick="checkWordCombo()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addCombo").click(function()
{
$("#comboContain").append('<option value="' + $("#newCombo").val() + '">' + $("#newCombo").val() + '</option>');
});
});
$('#comboContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var comboOptions = new Array();
$('form').submit(
function()
{
$('#comboContain > option:selected').each(
function(i)
{
comboOptions[i] = $(this).val();
});
//window.alert(comboOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can swap -->
<h3>Words that can be Swapped</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSwap"/>
<button id="addSwap">Insert</button>
<label for="swapContain">Select as many as you like:</label>
<select id="swapContain" name="comboSwap" multiple></select>
<button id="checkSwap" onclick="checkSwap()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSwap").click(function()
{
$("#swapContain").append('<option value="' + $("#newSwap").val() + '">' + $("#newSwap").val() + '</option>');
});
});
$('#swapContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var swapOptions = new Array();
$('form').submit(
function()
{
$('#swapContain > option:selected').each(
function(i)
{
swapOptions[i] = $(this).val();
});
//window.alert(swapOptions);
return false;
});
</script>
</fieldset>
</form>
<!-- User inputs words that can be use as Synonyms -->
<h3>Words that can be used as Synonyms</h3>
<form action="#" method="post">
<fieldset>
<input type="text" id="newSyn"/>
<button id="addSyn">Insert</button>
<label for="synContain">Select as many as you like:</label>
<select id="synContain" name="comboSyn" multiple></select>
<button id="checkSyn" onclick="checkSyn()">Insert into Array</button>
<script type="text/javascript">
$(document).ready(function()
{
$("#addSyn").click(function()
{
$("#synContain").append('<option value="' + $("#newSyn").val() + '">' + $("#newSyn").val() + '</option>');
});
});
$('#synContain option').each(
function(c)
{
$(this).val(c).text('option: ' + c);
});
var synOptions = new Array();
$('form').submit(
function()
{
$('#synContain > option:selected').each(
function(i)
{
synOptions[i] = $(this).val();
});
//window.alert(synOptions);
return false;
});
</script>
</fieldset>
</form>
<button onclick="generate_title()">Generate Titles</button>
<button onclick="displayList()">Click Me</button>
<script>
function displayList()
{
alert(coreOptions+ " " +comboOptions +" " +swapOptions+ " " +synOptions);
}
</script>
<div id="display"></div>
</body>
</html>
External Javascript
var check = ["Facebook", "MySpace", "Twitter"];
//document.getElementById("coreOptions");
//var checkX = check.splice(" ");
var checkY = document.getElementById("swapOptions");
var input_keywords =
[
[check, check],
//[checkY,checkY],
["Cordless-","Wireless"],
["Rechargeable+"],
].filter(function(item){
return item.length <= 80;
});
/*[
["Men", "Women", "Unisex"],
["1", "2", "3", "fourrrrrrrrrr"],
["Candy Color"],
["Spring"],
["Ski+"],
["Crochet"],
["Hip-hop"],
["Hat Beanie-"],
["One Size+"]].filter(function(item)
{
return item.length <= 80;
});
*/
/*
var input_keywords = [
["Women Men", "Men Women", "Unisex Women Men", "Unisex Men Women", "Unisex", "Womens Mens", "Mens Womens", "Unisex Womens Mens", "Unisex Mens Womens"],
["Fashion", "Trendy", "Stylish", "Korea Style"],
["Candy Color"],
["Spring", "Summer", "Winter"],
["Ski"],
["Crochet", "Knit", "Knitted"],
["Elastic", "Strechable"],
["Hip-hop", "Dance"],
["Hat", "Cap", "Beanie", "Hat Cap", "Hat Beanie", "Hat Cap Beanie"],
["One Size"]
].filter(function(item){
return item.length <= 80;
});
*/
var limit_count = 24;
var max_char_per_title = 80;
var sub_library = ["for=4", "you=u", "at=#", "two=2", "with=w", "adapter=adpt", "Monokini=Mono 9"].map( function (item)
{ return item.split("=");});
function calc_length(title)
{
return (title
.join(" ") + " ")
.replace("- ", " ")
.replace("+ ", " ")
.replace("* ", " ")
.replace(" ", " ")
.replace("\" ", " ")
.replace(" \"", " ")
.length - 1;
}
function get_all_titles(keywords)
{
var result_titles = [];
for(var i = 0; i < keywords.length; i ++)
{
var word_count = keywords[i].length;
var words = keywords[i];
var previous_count = result_titles.length;
if (previous_count == 0)
{
previous_count = word_count;
for (var sub_ii = 0 ; sub_ii < word_count; sub_ii++)
{
result_titles[sub_ii] = [];
result_titles[sub_ii][i] = words[sub_ii];
}
}
else
{
for (var sub_i = 0; sub_i < word_count; sub_i++)
{
for (var sub_ii = 0 ; sub_ii < previous_count; sub_ii++)
{
if (result_titles[previous_count * sub_i + sub_ii] == undefined)
{
result_titles[previous_count * sub_i + sub_ii] = result_titles[sub_ii ].slice();
}
result_titles[previous_count * sub_i + sub_ii][i] = words[sub_i];
}
}
}
}
return result_titles;
}
function substitute(title)
{
for (var subs_idx = 0 ; subs_idx < sub_library.length; subs_idx++)
{
var index = title.indexOf(sub_library[subs_idx][0]);
if (index >= 0)
{
title[index] = sub_library[subs_idx][1];
}
}
return title;
}
function shorten_title_length(titles)
{
var result = [];
var count = 0;
for (var i = 0 ; i < titles.length; i++)
{
if (calc_length(titles[i]) > max_char_per_title)
{
//substitute with the word in library
titles[i] = substitute(titles[i]);
// still too long, remove possible words.
if (calc_length(titles[i]) > max_char_per_title)
{
var words = titles[i];
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx].indexOf("/") == (words[word_idx].length - 1))
{
titles[i] = titles[i].splice(word_idx, 1);
}
}
titles[i] = words
}
}
if (calc_length(titles[i]) <= max_char_per_title)
{
result[count] = titles[i];
count++;
}
else
{
console.log(titles[i].join(" \ "));
}
}
return result;
}
function change_forward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "-")
{
if (word_idx != words.length - 1)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx + 1];
words[word_idx + 1] = tmp;
word_idx ++;
}
}
}
title = words;
return title;
}
function change_backward_position(title)
{
var words = title;
for (var word_idx = 0 ; word_idx < words.length; word_idx++)
{
if (words[word_idx][words[word_idx].length - 1] == "+")
{
if (word_idx != 0)
{
var tmp = words[word_idx];
words[word_idx] = words[word_idx - 1];
words[word_idx - 1] = tmp;
}
}
}
title = words;
return title;
}
function finalize(titles)
{
for (var title_idx = 0 ; title_idx < titles.length; title_idx++)
{
for (var word_idx = 0 ; word_idx < titles[title_idx].length; word_idx++)
{
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '+')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '-')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '/')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '"')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
if (titles[title_idx][word_idx][titles[title_idx][word_idx].length - 1] == '*')
titles[title_idx][word_idx] = titles[title_idx][word_idx].substring(0, titles[title_idx][word_idx].length - 1);
}
}
return titles;
}
function generate_title()
{
var all_titles = get_all_titles(input_keywords);
//Check keyword files provided by the user, that optional sub words are at least 24
if (all_titles.length < limit_count)
{
alert("not enough different titles");
}
//check total char per title
all_titles = shorten_title_length(all_titles);
// substitute half randomly.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = substitute(all_titles[i]);
}
}
//changing position backward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_backward_position(all_titles[i]);
}
}
//changing position forward.
for (var i = 0 ; i < all_titles.length; i++)
{
if (Math.random() > 0.5)
{
all_titles[i] = change_forward_position(all_titles[i]);
}
}
all_titles = finalize(all_titles);
// evaluate.....
for (var i = 0 ; i < all_titles.length; i++)
{
console.log(i);
console.log(all_titles[i].join(" \ "));
console.log(all_titles[i].length);
alert(all_titles);
}
}

Sorting table using javascript sort()

I am trying to sort a table. I've seen several jQuery and JavaScript solutions which do this through various means, however, haven't seen any that use JavaScript's native sort() method. Maybe I am wrong, but it seems to me that using sort() would be faster.
Below is my attempt, however, I am definitely missing something. Is what I am trying to do feasible, or should I abandon it? Ideally, I would like to stay away from innerHTML and jQuery. Thanks
var index = 0; //Index to sort on.
var a = document.getElementById('myTable').rows;
//sort() doesn't work on collection
var b = [];
for (var i = a.length >>> 0; i--;) {
b[i] = a[i];
}
var x_td, y_td;
b.sort(function(x, y) {
//Having to use getElementsByTagName is probably wrong
x_td = x.getElementsByTagName('td')[index].data;
y_td = y.getElementsByTagName('td')[index].data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
A td element doesn't have a .data property.
If you wanted the text content of the element, and if there's only a single text node, then use .firstChild before .data.
Then when that is done, you need to append the elements to the DOM. Sorting a JavaScript Array of elements doesn't have any impact on the DOM.
Also, instead of getElementsByTagName("td"), you can just use .cells.
b.sort(function(rowx, rowy) {
x_td = rowx.cells[index].firstChild.data;
y_td = rowy.cells[index].firstChild.data;
return x_td == y_td ? 0 : (x_td < y_td ? -1 : 1);
});
var parent = b[0].parentNode;
b.forEach(function(row) {
parent.appendChild(row);
});
If the content that you're comparing is numeric, you should convert the strings to numbers.
If they are text strings, then you should use .localeCompare().
return x_td.localeCompare(y_td);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>All Sorting Techniques</title>
<script type="text/javascript">
var a = [21,5,7,318,3,4,9,1,34,67,33,109,23,156,283];
function bubbleSort(a)
{
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("bublsrt").innerHTML = "Bubble Sort Result is: "+a;
}
var b = [1,3,4,5,7,9,21,23,33,34,67,109,156,283,318];
function binarySearch(b, elem){
var left = 0;
var right = b.length - 1;
while (left <= right){
var mid = parseInt((left + right)/2);
if (b[mid] == elem)
return mid;
else if (b[mid] < elem)
left = mid + 1;
else
right = mid - 1;
}
return b.length;
}
function searchbinary(){
var x = document.getElementById("binarysearchtb").value;
var element= binarySearch(b,x);
if(element==b.length)
{
alert("no. not found");
}
else
{
alert("Element is at the index number: "+ element);
}
}
function quicksort(a)
{
if (a.length == 0)
return [];
var left = new Array();
var right = new Array();
var pivot = a[0];
for (var i = 1; i < a.length; i++) {
if (a[i] < pivot) {
left.push(a[i]);
} else {
right.push(a[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
}
function quicksortresult()
{
quicksort(a);
document.getElementById("qcksrt").innerHTML = "Quick Sort Result is: "+quicksort(a);
}
function numeric(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault)
theEvent.preventDefault();
}
}
function insertionsorting(a)
{
var len = a.length;
var temp;
var i;
var j;
for (i=0; i < len; i++) {
temp = a[i];
for (j=i-1; j > -1 && a[j] > temp; j--) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
document.getElementById("insrtsrt").innerHTML = "Insertion Sort Result is: "+a;
}
function hiddendiv()
{
document.getElementById("binarytbdiv").style.display = "none";
document.getElementById("Insertnotbdiv").style.display = "none";
}
function binarydivshow()
{
document.getElementById("binarytbdiv").style.display = "block";
}
function insertnodivshow()
{
document.getElementById("Insertnotbdiv").style.display = "block";
}
function insertno(a)
{
var extrano = document.getElementById("Insertnotb").value;
var b= a.push(extrano);
var change;
do {
change = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
change = true;
}
}
} while (change);
document.getElementById("insrtnosearch").innerHTML = "Sorted List is: "+a;
alert("Index of "+extrano +" is " +a.indexOf(extrano));
}
</script>
</head>
<body onload="hiddendiv()">
<h1 align="center">All Type Of Sorting</h1>
<p align="center">Your Array is : 21,5,7,318,3,4,9,1,34,67,33,109,23,156,283</p>
<div id="main_div" align="center">
<div id="bubblesort">
<input type="button" id="bubblesortbutton" onclick="bubbleSort(a)" value="Bubble Sort">
<p id="bublsrt"></p>
</div><br>
<div id="quicksort">
<input type="button" id="quicksortbutton" onclick="quicksortresult()" value="Quick Sort">
<p id="qcksrt"></p>
</div><br>
<div id="insertionsort">
<input type="button" id="insertionsortbutton" onclick="insertionsorting(a)" value="Insertion Sort">
<p id="insrtsrt"></p>
</div><br>
<div id="binarysearch">
<input type="button" id="binarysearchbutton" onclick="binarydivshow();" value="Binary Search">
<div id="binarytbdiv">
<input type="text" id="binarysearchtb" placeholder="Enter a Number" onkeypress="numeric(event)"><br>
<input type="button" id="binarysearchtbbutton" value="Submit" onclick="searchbinary()">
<p id="binarysrch">Sorted List is : 1,3,4,5,7,9,21,23,33,34,67,109,156,283,318</p>
</div>
</div><br>
<div id="Insertno">
<input type="button" id="insertno" onclick="insertnodivshow()" value="Insert A Number">
<div id="Insertnotbdiv">
<input type="text" id="Insertnotb" placeholder="Enter a Number" onkeypress="numeric(event);"><br>
<input type="button" id="Insertnotbbutton" value="Submit" onclick="insertno(a)">
<p id="insrtnosearch"></p>
</div>
</div>
</div>
</body>
</html>

Categories

Resources