JavaScript not further executed once a button is disabled - javascript

I am using next and prev buttons so one question will be shown at a time, however, once next or prev buttons are disabled, the other button doesn't work anymore either. Here's my code:
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
function next() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 1) {
document.getElementById("next").disabled = true;
} else {
console.log(i);
qElems[i + 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i + 1] = 1;
}
break;
}
}
}
function prev() {
var qElems = [];
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 4) {
document.getElementById("prev").disabled = true;
} else {
qElems[i - 1].style.display = 'block';
qElems[i].style.display = 'none';
showing[i - 1] = 1;
}
break;
}
}
}

I think you want this simplified script
I had to guess the HTML, but there is only one function.
window.addEventListener("load", function() {
let showing = 0;
const questions = document.querySelectorAll(".q");
questions[showing].style.display = "block";
const next = document.getElementById("next");
const prev = document.getElementById("prev");
document.getElementById("nav").addEventListener("click", function(e) {
var but = e.target, dir;
if (but.id === "prev") dir = -1;
else if (but.id === "next") dir = 1;
else return; // not a button
questions[showing].style.display = "none"; // hide current
showing += dir; // up or down
next.disabled = showing === questions.length-1;
if (showing <= 0) showing = 0;
prev.disabled = showing === 0
questions[showing].style.display = "block";
})
})
.q { display:none }
<div class="q" id="q0">Question 0</div>
<hr/>
<div class="q" id="q1">Question 1</div>
<hr/>
<div class="q" id="q2">Question 2</div>
<hr/>
<div class="q" id="q3">Question 3</div>
<hr/>
<div id="nav">
<button type="button" id="prev" disabled>Prev</button>
<button type="button" id="next">Next</button>
</div>

Since this is a quiet interesting java script task, Im doing my own solution.
Hope this matches the requirement.
I have created 4 divs of which first one is only displayed at first. Remaining divs are placed hidden. On clicking next, the divs are displayed according to index. Once the last and first indexes are interpreted, the respective next and previous buttons are enabled and disabled.
var showing = [1, 0, 0, 0];
var questions = ['q0', 'q1', 'q2', 'q3'];
var qElems = [];
function initialize() {
for (var i = 0; i < questions.length; i++) {
qElems.push(document.getElementById(questions[i]));
}
}
function updatevisibilitystatus(showindex, hideindex) {
qElems[showindex].style.display = 'block';
qElems[hideindex].style.display = 'none';
showing[showindex] = 1;
}
function next() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == showing.length - 2) {
document.getElementById("next").disabled = true;
}
updatevisibilitystatus(i + 1, i);
document.getElementById("prev").disabled = false;
break;
}
}
}
function prev() {
for (var i = 0; i <= showing.length; i++) {
if (showing[i] == 1) {
showing[i] = 0;
if (i == 1) {
document.getElementById("prev").disabled = true;
}
updatevisibilitystatus(i - 1, i);
document.getElementById("next").disabled = false;
break;
}
}
}
<body onload="initialize()">
<div id="q0" style="display: block;">Q0</div>
<div id="q1" style="display: none;">Q1</div>
<div id="q2" style="display: none;">Q2</div>
<div id="q3" style="display: none;">Q3</div>
<button id="prev" disabled onclick="prev()">Prev</button>
<button id="next" onclick="next()">Next</button>
</body>

Related

How to make value become 0 in textbox?

I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />

How to not overwrite button actions?

I have a table with random words and I want specific words to be grayed out when clicking one of the buttons. On the second press of the same button, the words that weren’t grayed on the first click are now gray, and the rest go back to being white (the second press is like inverting the output in a way). Here’s my code:
var pressCount = [0, 0, 0];
var table = document.getElementsByTagName("td");
document.body.addEventListener("click", function(event) {
var target = event.target;
var id = target.id;
var index;
if (id === "b1") {
index = 0;
} else if (id === "b2") {
index = 1;
} else if (id === "b3") {
index = 2;
} else if (id === "reset") {
reset();
return;
} else {
return;
}
pressCount[index]++;
if (pressCount[index] === 1) {
target.style.backgroundColor = "green";
var wordsToGray;
if (index === 0) {
wordsToGray = ["Behave", "Reach"];
} else if (index === 1) {
wordsToGray = ["Take", "Behave", "Utopia"];
} else if (index === 2) {
wordsToGray = ["Like", "Median"];
}
for (var i = 0; i < table.length; i++) {
if(wordsToGray.includes(table[i].innerHTML)) {
table[i].style.color = "gray";
} else {
table[i].style.color = "white";
}
}
} else if (pressCount[index] === 2) {
target.style.backgroundColor = "red";
var wordsToGray;
if (index === 0) {
wordsToGray = ["Take", "Riddle", "Like", "Move", "Median", "Utopia", "Walk"];
} else if (index === 1) {
wordsToGray = ["Riddle", "Like", "Move", "Reach", "Median", "Walk"];
} else if (index === 2) {
wordsToGray = ["Take", "Behave", "Riddle", "Move", "Reach", "Utopia", "Walk"];
}
for (var i = 0; i < table.length; i++) {
if(wordsToGray.includes(table[i].innerHTML)) {
table[i].style.color = "gray";
} else {
table[i].style.color = "white";
}
}
} else {
target.style.backgroundColor = "";
pressCount[index] = 0;
}
});
function reset() {
var table = document.getElementsByTagName("td");
for (var i = 0; i < table.length; i++) {
table[i].style.color = "white";
}
var b1Button = document.getElementById("b1");
b1Button.style.backgroundColor = "";
var b2Button = document.getElementById("b2");
b2Button.style.backgroundColor = "";
var b3Button = document.getElementById("b3");
b3Button.style.backgroundColor = "";
pressCount = [0, 0, 0];
}
table {
font-size: 30px;
width: 25%;
text-align: center;
border: none;
background-color: black;
<table>
<tr>
<td style="color:white;">Take</td>
<td style="color:white;">Behave</td>
<td style="color:white;">Riddle</td>
</tr>
<tr>
<td style="color:white;">Like</td>
<td style="color:white;">Move</td>
<td style="color:white;">Reach</td>
</tr>
<tr>
<td style="color:white;">Median</td>
<td style="color:white;">Utopia</td>
<td style="color:white;">Walk</td>
</tr>
</table>
<br>
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<button id="b3">Button 3</button>
<button id="reset">RESET</button>
The problem is that when, for example, I press button 2 once and then button 1 once, the output shows only the words "Behave" and "Reach" grayed out (it’s the action on the first press of button 1). What I want the output to be, is the words "Take", "Behave", "Reach" and "Utopia" being grayed out. Meaning the action of button 2 isn’t overwritten.
I’m also thinking of having an action on the third button press that resets the buttons actions but I haven’t thought on how this is achievable and I’m getting ahead of myself here.

Implementing slide puzzle using Javascript

First off, thank you for reading this question. With this javascript code, I'm trying to implement a 4x4 slide number puzzle, which looks like this when completed. :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 [blank]
Each number are represented by .gif number files which are on the same folder where this HTML file is.
When a user clicks "START" button below the puzzle, it shuffles pieces by repetitively swapping randomly chosen two pieces. (shuffle function)
When a user clicks a piece adjacent to the blank piece then it swaps the two. (movePiece function)
But the problem is when I click the START button and the piece adjacent to the blank piece, nothing happens.. even though except for this code's logic and algorithm is not different from the answer that my instructor's given and I can't find where is causing this problem.
Can anyone help me find out where is wrong with this code?
Any advice would be much appreciated.
<html>
<head>
<title>15 Puzzle Game</title>
<meta name="generator" content="Microsoft FrontPage 4.0" charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str){
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete()
{
if(completed) return 0;
for(var i = 1; i <= document.images.length; i++){
if(document.images[i-1].src != i+".gif") return 0;
}
return 1;
}
function getNum(idx){
var index = idx - 1;
var token[] = tokenize("/",document.images[index].src);
var numOfTokens = tokenize("/",document.images[index].src).length;
var num = tokenize(".", token[numOfTokens-1])[0];
return Number(num);
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
for (i=0;i<iter;i++)
{
var ranNum = Math.floor(Math.random()*16)+1;
var newNum = newIndex(ranNum);
var temp = puzzles[ranNum-1];
puzzles[ranNum-1] = puzzles[newNum-1];
puzzles[newNum-1] = temp;
}
}
for(i=1;i<document.images.length+1;i++){
document.images[i-1].src = ""+puzzles[i-1]+".gif";
}
completed = false;
}
function movePiece(idx)
{
x = getX(idx);
y = getY(idx);
var flag = 0;
var tempIdx;
for(i=-1; i<=1 ; i=i+2){
if ((x==2)||(x==3)) dir=i;
else dir=(x==1)?1:-1;
var tmpx= (x+dir);
tempIdx = getIndex(tmpx,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
for(i=-1; i<=1 ; i=i+2){
if ((y==2)||(y==3)) dir=i;
else dir=(y==1)?1:-1;
var tmpy= (y+dir);
tempIdx = getIndex(x,y);
if(getNum(tempIdx) == 16){ flag = 1; midx=tempIdx; }
}
if (flag == 1){
document.images[midx-1].src = document.images[idx-1].src;
document.images[idx-1].src = "16.gif";
}
if(isComplete()) alert('Congratulation!');
completed = true;
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>
javascript
and this is working code
<html>
<head>
<title>15 Puzzle Game</title>
<meta charset="UTF-8">
<script language="JavaScript">
var completed=true;
function tokenize(sep,str)
{
tokens = new Array();
i=0;
while(1)
{
idx=str.indexOf(sep);
if(idx == -1)
{
if(str.length>0)
{
tokens[i]=str;
}
break;
}
tokens[i++]=str.substring(0,idx);
str=str.substr(idx+1);
}
return tokens;
}
function getX(idx)
{
var rest=idx-Math.floor(idx/4)*4;
return (rest==0)?4:rest;
}
function getY(idx)
{
return Math.floor((idx-1)/4)+1;
}
function getIndex(x,y)
{
return x+(y-1)*4;
}
function newDirection(pos)
{
var dir;
if ((pos==2)||(pos==3)) dir=(Math.floor(Math.random()+0.5)==0)?-1:1;
else dir=(pos==1)?1:-1;
return (pos+dir);
}
function newIndex(idx)
{
var x,y;
x=getX(idx);
y=getY(idx);
if (Math.floor(Math.random()+0.5)==0) x=newDirection(x);
else y=newDirection(y);
return getIndex(x,y);
}
function isComplete() {
if(completed)
return false;
var prev = getPiece(1);
for(var i = 2; i < 17; i++) {
var current = getPiece(i);
if(current != prev+1)
return false;
prev = current;
}
return true;
}
function shuffle()
{
var puzzles=new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16);
iter=Math.floor(Math.random()*200+0.5)+100;
var blank = 15;
for (i=0; i<iter; i++)
{
var move = newIndex(blank+1)-1;
var t = puzzles[blank];
puzzles[blank] = puzzles[move];
puzzles[move] = t;
blank = move;
}
for(i = 0; i < 16; i++)
document.images[i].src = ""+puzzles[i]+".gif";
completed = false;
}
function movePiece(idx)
{
var current = getPiece(idx);
if(current == 16)
return;
var x = getX(idx);
var y = getY(idx);
var flag=false, midx=idx;
var dx = [0, 0, -1, 1], dy = [-1, 1, 0, 0];
for(var i = 0; i < 4; i++) {
if(1 <= x+dx[i] && x+dx[i] <= 4 && 1 <= y+dy[i] && y+dy[i] <= 4) {
if(getPiece(getIndex(x+dx[i], y+dy[i])) == 16) {
flag = true;
midx = getIndex(x+dx[i], y+dy[i]);
break;
}
}
}
if(flag) {
var t = document.images[idx-1].src;
document.images[idx-1].src = document.images[midx-1].src;
document.images[midx-1].src = t;
}
if(isComplete()) {
alert("Congratulation!");
completed = true;
}
}
function getPiece(idx) {
idx--;
var len = tokenize("/", document.images[idx].src).length;
return Number(tokenize(".", tokenize("/", document.images[idx].src)[len-1])[0]);
}
</script>
</head>
<body bgcolor="silver" text="black" link="#0000EE" vlink="#551A8B" alink="red">
<h2 align="center">
15 Puzzle</h2>
<div align="center">
<table border>
<tr>
<td width="50%" align="center">
<script language="JavaScript">
with(window.document)
{
open();
writeln('<table border=1 cellpadding=0 cellspacing=1>');
for(var i=1;i<17;i++)
{
if(i==1 || i==5 || i==9 || i==13 )
{
writeln('<tr>');
}
writeln(' <td width=49 height=49>');
writeln(' <a href=JavaScript:movePiece('+i+');>');
writeln(' <img src=',i,'.gif border=0 width=49 height=49 name=i',i,'></a>');
writeln(' </td>');
if(i==4 || i==8 || i==12 || i==16 )
{
writeln('</tr>');
}
}
writeln('</table>');
close();
}
</script>
</td>
</tr>
</table>
</div>
<p align="center">
<br>
</p>
<form method="get">
<p align="center">
<input type="button" value="START" onClick="shuffle()"></p>
</form>
</body>
</html>
The code you provided isn't a good read, so I've created my own version in React. I hope it'll help you to figure things out or at least inspire you to learn React.
https://codesandbox.io/s/wq8n9k5jr7

code that displays words, JS Jquery

Code Link: http://jsbin.com/lozifokuzi/1/edit?html,js,output should display 16 words but it displays only 15 words (The words written in Hebrew).
The code is written in languages ​​JavaScript and jQuery.
$(document).ready(function () {
// creat array of objects, DetermineIDs
var words = new Array(16);
for (var i = 0; i < words.length; i++) {
words[i] = new Object();
words[i].id = i + 1;
}
//insert into objects words
words[0].word = "קוף";
words[1].word = "קוף";
words[2].word = "אריה";
words[3].word = "אריה";
words[4].word = "נמר";
words[5].word = "נמר";
words[6].word = "טלפון";
words[7].word = "טלפון";
words[8].word = "מחשב";
words[9].word = "מחשב";
words[10].word = "מקלדת";
words[11].word = "מקלדת";
words[12].word = "אוגר";
words[13].word = "אוגר";
words[14].word = "עכבר";
words[15].word = "עכבר";
//Determine locations
var ret=Random(loc);
var random = 0;
for (var i = 0; i < words.length; i++) {
words[i].loca=ret[0];
loc=ret[1];
ret = Random(loc);
}
//write the words
for (var i = 0; i < 16; i++) {
$("#c" + (words[i].loca)).html(words[i].word);
}
});
function RandomC(ezer, random) {
for (var i = 0; i <= 16; i++) {
if (ezer[i] == random) {
return true;
}
}
return false;
}
function Random(lq) {
var ezer = new Array(16);
for (var i = 0; i < 16; i++) {
ezer[i] = lq[i];
}
var random = 0;
while ((random < 1 || random > 17) || RandomC(ezer, random)) {
random = parseInt(Math.random() * 100);
}
for (var i = 0; i < lq.length; i++) {
if (lq[i] == null) {
ezer[i] = random;
break;
}
}
var arr = new Array(2);
arr[0] = random;
arr[1] = ezer;
return arr;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<article>
<div id="l1">
<p id="c1"></p>
<p id ="c2"></p>
<p id="c3"></p>
<p id="c4"></p>
</div>
<div id="l2">
<p id="c5"></p>
<p id="c6"></p>
<p id="c7"></p>
<p id="c8"></p>
</div>
<div id="l3">
<p id="c9"></p>
<p id="c10"></p>
<p id="c11"></p>
<p id="c12"></p>
</div>
<div id="l4">
<p id="c13"></p>
<p id="c14"></p>
<p id="c15"></p>
<p id="c16"></p>
</div>
</article>
</body>
</html>
Can anyone help?
You have 17 in funciton Random() while loop:
while ((random < 1 || random > 17) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
make it 16:
while ((random < 1 || random > 16) || RandomC(ezer, random))
{
random = parseInt(Math.random() * 100);
}
You problem is that you have 16 element from 1 to 16, and your random function gives 16 random numbers from 1 to 17, in case returned range has number 17 it lacks something from 1 to 16, which means your p element of that nubmer doesn't get filled with content.

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