I have got 2 js functions and in a function show I want to get the index of the current visible element, but it always alerts 0. It doesn't seem to check, if function navigate_right() has changed the ids of the p elements or not.So how can I modify it so that it runs properly?
<html>
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<p style="display:block" id="p">some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value="left" onclick="show()" />
<input type="button" value="right" onclick="navigate_right()" id="right" />
<script>
var p = document.getElementsByTagName("p");
function navigate_right() {
for (var i = 1; i < p.length; i++) {
if (p[i - 1].style.display == 'block') {
p[i].style.display = 'block';
p[i - 1].style.display = 'none';
return;
}
}
}
function show() {
var c = document.getElementsByTagName("p");
var t;
for (var i = 0; i < p.length; i++) {
if (c[i].id = "vis") {
t = i;
alert(t);
return;
}
}
}
</script>
</html>
EDIT! there should be alert t;t is for index of a current paragraph visible
NOW IT WORKS!I have corrected some silly mistakes. But thanx everyone for help anyway
var p = document.getElementsByTagName("p");
function navigate_right() {
for(var i = 1; i <p.length; i++){
if(p[i-1].style.display == 'block') {
p[i].style.display = 'block';
p[i].id = "vis";
p[i-1].style.display ='none';
p[i-1].removeAttribute("id");
return;
}
}
}
function show(){
var c = document.getElementsByTagName("p");
var t;
for (var i = 0; i < p.length; i++) {
if(c[i].id == "vis") {
t = i;
alert(t);
return;
}
}
}
c[i].id = "vis" is setting the ID. The assignment evaluates to true so the code always goes into the if body first time round the loop. That's why i is always 0.
You want c[i].id === "vis" (or at least c[i].id == "vis").
Related
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>
i am creating a tic tac toe game using javascript and i got it to work. However my only issue is that the reset button wont work. I have looked at other posts that involve a reset button but im not getting it to work. Also the function i tried using to for the reset button is document.getElementById("myForm").reset();
I'm a beginner doing this so im sorry if i made a mistake that seems apparent.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tic Tac Toe Game </title>
<meta charset="UTF-8" />
</head>
<style>
body{
font-family: san-serif;
background:#333;
color:black;
background-color: yellow;
}
td{
width:80px;
height:80px;
border: solid 3px black;
text-align:center;
font-size:30pt;
}
.tictactoe{
text-align:center;
margin:0 auto;
width:40%;
padding:10px 50px 20px
}
.board{
float:left;
margin-left:20px;
width:60%;
}
.player{
float:left;
width:15%;
}
.player-points{
font-size:50pt;
}
h1{
float: center;
}
</style>
<h1 align="center"> Tic-Tac-Toe</h1>
<div class="tictactoe">
<div class="player">
Player 1
<div class="player-points" id="player1">
0
</div>
</div>
<table id="game" class="board">
</table>
<div class="player">
Player 2
<div id="player2" class="player-points">0</div>
</div>
<input type='reset' style='width:100px;margin:0 50%;position:relative;left:-50px;'>
<div class="clear"></div>
</div>
<script>
var winners = new Array();
//---------------------------------------------------------------
// both player selections are used to keep track of the boxes
// that the user has clicked on
var player1pics = new Array();
var player2pics = new Array();
//-----------------------------------------------------------------------------
var timer;
var numberOfPlayers = 2;
var currentPlayer = 0;
var move = 0;
var points1 = 0;
var points2 = 0;
var gridsize = 3; // Used for 3x3 Grid
/*
Function drawboard is manily to check if player 1
or player 2 has won the round and if one of those
players wins, then the points will update
*/
function drawBoard() {
var Parent = document.getElementById("game");
var counter = 1;
while (Parent.hasChildNodes()) {
Parent.removeChild(Parent.firstChild);
}
for (s = 0; s < 3; s++) {
var row = document.createElement("tr");
for (r = 0; r < 3; r++) {
var col = document.createElement("td");
col.id = counter;
col.innerHTML = counter;
var handler = function(e) {
if (currentPlayer == 0) {
this.innerHTML = "X";
player1pics.push(parseInt(this.id));
player1pics.sort(function(a, b) { return a - b });
}
else {
this.innerHTML = "O";
player2pics.push(parseInt(this.id));
player2pics.sort(function(a, b) { return a - b });
}
move++;
var isWin = checkWinner();
if (isWin)
{
if(currentPlayer == 0)
points1++;
else
points2++;
document.getElementById("player1").innerHTML = points1;
document.getElementById("player2").innerHTML = points2;
reset();
drawBoard();
}
else
{
if (currentPlayer == 0)
currentPlayer = 1;
else
currentPlayer = 0;
this.removeEventListener('click', arguments.callee);
}
};
col.addEventListener('click', handler);
row.appendChild(col);
counter++;
}
Parent.appendChild(row);
}
loadAnswers();
}
function reset()
{
currentPlayer = 0;
player1pics = new Array();
player2pics = new Array();
}
// Possible ways of Winning
function loadAnswers()
{
winners.push([1, 2, 3]);
winners.push([4, 5, 6]);
winners.push([7, 8, 9]);
winners.push([1, 4, 7]);
winners.push([2, 5, 8]);
winners.push([3, 6, 9]);
winners.push([1, 5, 9]);
winners.push([3, 5, 7]);
}
//Function checkWinner sees if the player has a winning method by looking at the selections
function checkWinner() {
var win = false;
var playerSelections = new Array();
if (currentPlayer == 0)
playerSelections = player1pics;
else
playerSelections = player2pics;
if (playerSelections.length >= gridsize) {
for (i = 0; i < winners.length; i++) {
var sets = winners[i];
var setFound = true;
for (r = 0; r < sets.length; r++) {
var found = false;
for (s = 0; s < playerSelections.length; s++) {
if (sets[r] == playerSelections[s]) {
found = true;
break;
}
}
if (found == false) {
setFound = false;
break;
}
}
if (setFound == true) {
win = true;
break;
}
}
}
return win;
}
window.addEventListener('load', function(){
drawBoard();
});
</script>
</html>
Mitchell,
The click event is not attached to the reset button and the 'drawboard' function isn't called on reset button click. you may have to make the below changes:
<input type='reset' style='width:100px;margin:0 50%;position:relative;left:-50px;' onclick="reset()">
function reset()
{
currentPlayer = 0;
player1pics = new Array();
player2pics = new Array();
drawBoard();
}
My code can be found here: https://www.w3schools.com/code/tryit.asp?filename=FHC2UOT0RQX6
The program accepts an array var array=[1,0,1,0,1,1,0,0,0] and solves the pseudoternary encoding scheme. All i want to do is simple. Insead of changing the elements of the array(when i want to insert a different input), i want to use the input text and take the values from it and when i press enter or the submit button, it will solve the problem depending on the user inputs. Is that possible to take the values of the text input and make them act as an array ?
Here is the script below but it is better to see the whole code, use the link above.
<script type="text/javascript">
var array=[1,0,1,0,1,1,0,0,0]; //input here
var text="";
for(var b=0;b<array.length;b++)
{
text+=array[b];
}
document.getElementById('enc').innerHTML=text;
pseudo(array);
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
for(var b=0;b<array.length;b++)
if(a[b]===1)
{
count++;
document.write('<img src="http://i.imgur.com/30DU9iC.png">');
}
else if(a[b]===0)
{
count++;
pulse=!pulse; //toggles boolean value each time it finds zero
if(pulse===true) //pulse shows up
{
document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
}
else{
document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
}
}
}
</script>
Actually you want to write your code inside a function and call the function onload and onclick respectively. Try this, http://www.w3schools.com/code/tryit.asp?filename=FALV2XZQ7V36
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
function loading() {
for (var b = 0; b < array.length; b++) {
text += array[b];
}
document.getElementById('enc').innerHTML = text;
pseudo(array);
}
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
var output = '';
var b = 0;
for (b = 0; b < a.length; b++)
if (a[b] === 1) {
count++;
//document.write('<p class="w3-center w3-text-red">'+'Step '+count+': No line'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/30DU9iC.png">');
output += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
//document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes up'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
output += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
// document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes down'+'<br>'+'</p>');
//document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
output += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
document.getElementById("js").innerHTML = output;
}
function gettext() {
var inputText = document.getElementById("tf").value;
var inparray = [inputText.length];
for (i in inputText) {
inparray[i] = parseInt(inputText[i]);
}
document.getElementById('enc').innerHTML = inputText;
pseudo(inparray);
}
body {} .pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
<html>
<head>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<!-- <link rel="stylesheet" href="style.css" type="text/css"/>-->
<h4>Use this input </h4>
<input type="text" id="tf"></input>
<input type="button" style="width:50px;" value="solve" onclick="gettext()" id="tf"></input>
</head>
<body onload="loading()" ;>
<h1>Illustration of pseudoternary encoding scheme </h1>
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center">
</div>
</body>
</html>
Note, <input> element is self-closing. <input> element should be child nodes of <body> element instead of <head> element. id of element in document should be unique. Replace duplicate "tf" id at input elements with unique values. Remove <script> element from being child node of div element. Place <script> element before closing </body> tag. Substitute concatenating .innerHTML for document.write()
Attach click event to input type="button", use String.prototype.split() with parameter "" to create an array from input type="text" .value, Array.prototype.map() with parameter Number to convert String to Number values. Assign resulting array to array variable. Set #js .innerHTML to empty string before calling function again with array as parameter.
<!DOCTYPE html>
<html>
<head>
<style>
body {}
.pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
</style>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h4 style="margin-top:240px;position:absolute">Use this input </h4>
<h1>Illustration of pseudoternary encoding scheme </h1>
<input type="text" style="position:relative" id="tf">
<input type="button" style="position:relative;width:50px;" value="solve" id="button">
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center"> </div>
<script>
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
var enc = document.getElementById("enc");
var button = document.getElementById("button");
var tf = document.getElementById("tf");
var center = document.getElementById("js");
for (var b = 0; b < array.length; b++) {
text += array[b];
}
enc.innerHTML = text;
pseudo(array);
function pseudo(a) {
var pulse = false;
var count = 0;
for (var b = 0; b < array.length; b++)
if (a[b] === 1) {
count++;
center.innerHTML += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
center.innerHTML += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
center.innerHTML += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
}
button.onclick = function() {
array = tf.value.split("").map(Number);
enc.innerHTML = array.join("");
console.log(array, enc);
center.innerHTML = "";
pseudo(array)
}
</script>
</body>
</html>
All I want to do is:
there are 7 numbers and 7 divs, they are linked to each other (nr 0 it's in a relationship with div 0)
when one of the numbers is clicked, it should collapse all the other divs which are not selected
it can be selected more at one time
To sum up, basically, the page has some labels with numbers and 7 divs which are all displayed by default (the divs), but when one or more of them are chosen by clicking on the numbers, the page should display only the chosen divs.
This is what I've been trying to do:
for(var i = 0; i <= 6; i++) {
if(i != (floors[i])) {
$("#lvl" + floors[i]).slideUp();
}
}
More code:
http://jsfiddle.net/LSjg4/
Try
var floors = [];
var $lvls = $('.lvl'), $nrs = $(".nr");
$nrs.click(function () {
var $nr = $(this), index = $nrs.index($nr), $lvl = $lvls.eq(index);
$lvl.add($nr).toggleClass('active');
if($nr.hasClass('active')){
$lvls.not('.active').slideUp();
$lvl.slideDown();
$nr.css("background-color", "#1b7664");
$nr.css("border-color", "#236959");
floors.push(($nr).text());
} else {
$nr.css("background-color", "#02c099");
$nr.css("border-color", "#13a480");
if($nrs.filter('.active').length == 0){
$lvls.slideDown();
} else {
$lvls.not('.active').slideUp();
}
var text = $nr.text();
floors.splice($.inArray(text, floors), 1);
}
console.log('floors', JSON.stringify(floors))
});
Demo: Fiddle
I corrected a few things in your code. Here is the below working code and link to it in jsfiddle.
There was a data type mismatch(comparing string and int). When matching whether it exists in floors array, the code was checking floors[i] only whereas the i can be any position in floors.
var floors = [];
$(".nr").click(function () {
var state = $(this).data('state');
state = !state;
if (state) {
$(this).css("background-color", "#1b7664");
$(this).css("border-color", "#236959");
floors.push(parseInt($(this).text()));
console.log(floors);
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
} else {
$(this).css("background-color", "#02c099");
$(this).css("border-color", "#13a480");
for (var i = 0; i < floors.length; i++) {
if (floors[i] == parseInt($(this).text()))
floors.splice(i, 1);
}
for(var i = 0; i <= 6; i++) {
ret = $.inArray(i, floors);
if(ret==-1) {
$("#lvl" + i).slideUp();
}
else {
$("#lvl" + i).slideDown();
}
}
}
$(this).data('state', state);
});
Demo Here: http://jsfiddle.net/bFe9T/
I believe this is what you're looking for:
$(".nr").click(function () {
$(this).toggleClass('selected');
$('.nr').each(function(){
var $target = $('#lvl'+$(this).text());
if($(this).is('.selected'))
$target.slideDown();
else
$target.slideUp();
});
});
Note that instead of changing the CSS properties I set up a class for the selected elements
Demo fiddle
Try this
$(".nr").click(function () {
//alert($(this).attr("data-select"));
if($(this).attr("data-select") === "1") {
$(this).attr("data-select","0");
} else {
$(this).attr("data-select","1");
}
$(".nr").each(function(){
if($(this).attr("data-select") === "1") {
var id = $(this).text();
$("div#lvl"+id).slideDown();
} else {
var id1 = $(this).text();
$("div#lvl"+id1).slideUp();
}
});
});
FIDDLE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideUp demo</title>
<style>
.norm { background:#cccccc; margin:3px; width:80px;height:40px; float:left;color:#000000 }
.faded { background:#ffffff; margin:3px; width:80px;height:40px; float:left;color:#ffffff }
.btn{width:80px;}
</style>
<script src="http://code.jquery.com/jquery-1.8.1.js"></script>
</head>
<body>
<button class="btn" onClick="show(1)">1</button>
<button class="btn" onClick="show(2)">2</button>
<button class="btn" onClick="show(3)">3</button>
<button class="btn" onClick="show(4)">4</button>
<button class="btn" onClick="reset()">Reset</button>
<div class="norm" id="slide1">1</div>
<div class="norm" id="slide2">2</div>
<div class="norm" id="slide3">3</div>
<div class="norm" id="slide4">4</div>
<div></div>
<script>
var save = new Array();
function show(indx){
if($.inArray(indx, save)==-1){
save.push(indx);
for(var i=0;i<5;i++){
if($.inArray(i, save)==-1){
$('#slide'+i).attr('class','faded');
}
else{
$('#slide'+i).attr('class','norm');
}
}
}
}
function reset(){
save = new Array();
for(var i=0;i<5;i++){
$('#slide'+i).attr('class','norm');
}
}
</script>
</body>
</html>
I would like to check if any div contains all words entered in an input field. However, currently I am stuck in a situation that as soon as a space is entered, it starts all over, and thus sort of acts like an OR operator instead of an AND operator. Could anyone please push me in the right direction? Thanks a lot!
This is what I have so far:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (divs[h].innerHTML.indexOf(words[i]) == -1) {
divs[h].style.backgroundColor = '#fff';
}
else {
divs[h].style.backgroundColor = '#ddd';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Apparently I was not very clear. My apologies.
What direction do I need to go to make it in Javascript so that it looks for if a div contains AND words[0] AND words[1] AND words[2], etc (so, in any random order)?
Right now when a split takes place, the function starts all over.
Need to also check the length of each query word:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (words[i].length > 0 && divs[h].innerHTML.indexOf(words[i]) >= 0) {
divs[h].style.backgroundColor = '#ddd';
break;
}
else {
divs[h].style.backgroundColor = '#fff';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Try my code :
HMTL :
<div class="search">
<div>aa cC abcc ac ad</div>
<div>ab ba bb bcc</div>
<div>bb cc dd ee cc</div>
</div>
<span>Search: </span><input type="text">
CSS :
div{
border:solid 1px #1e2a29;
margin-bottom:10px;
padding:5px;
width:auto;
}
.matched{
background-color:#f8dda9;
border:1px solid #edd19b;
margin:-1px;
border-radius:2px;
}
input[type="text"]{
margin-left:10px;
}
Javascript :
$(document).ready(function(){
$('.search > div ').each(function(i, el){
$(this).data('originalText', $(this).html());
});
$('input').keyup(function(e){
var _val = $(this).val();
var _span = '<span class="matched" >$1</span>';
$('.search div ').each(function(i, el){
var _originalVal = $(el).data('originalText');
var re = new RegExp('('+_val+')', "ig");
if(_val.length > 1 && re.test(_originalVal) >=0 ){
$(el).html(_originalVal.replace(re, _span));
}else{
$(el).html(_originalVal);
}
});
});
})
See DEMO