So I'm totally not into javascript, sadly I need to use it for a small project. I'm making a checklist but I can't get a variable to write to a modal box. I left out the rest of the checklist because that would be a lot of unnecessary HTML.
What I want to achieve:
The if statement with the count is going to calculate how many points you got correct on the checklist. Then he will write this calculation to the modal box/window. But I can't manage to get the variable trough. Is it a scope problem perhaps?
My code
<a class="subbtn" href="#popup1" onclick="checkboxes()">Verstuur</a>
<script>
$(document).ready(function () {
$(".checklist").contents().find(":checkbox").bind('change', function () {
val = this.checked; //<---
$(this).parent().toggleClass('checked');
});
$(".checklist").contents().find(":checkbox").bind('focus', function () {
val = this.focused; //<---
$('.focus').removeClass('focus');
$(this).parent().addClass('focus');
});
});
</script>
<script>
function checkboxes(variable) {
var inputElems = document.getElementsByTagName("input")
, count = 0;
for (var i = 0; i < inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
count++;
}
}
if (count == '0') {
document.getElementsByClassName('content').innerHTML = variable;
}
else if (count == '5') {
alert('Not good')
}
else if (count < 5) {
alert('decent')
}
else if (count > '5') {
alert('Better')
}
}
</script>
</section>
</div>
<div id="popup1" class="overlay">
<div class="popup">
<h2>Je scoort</h2> <a class="close" href="#">×</a>
<div class="content">
<script>variable</script>
</div>
</div>
The problem seems to be the fact that you get a list. You can use that to get a single element with the classname.
function checkboxes(variable) {
var variable = "mooi";
var inputElems = document.getElementsByTagName("input")
, count = 0;
for (var i = 0; i < inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true) {
count++;
}
}
if (count == '0') {
document.querySelector('.content').innerHTML = variable;
}
else if (count == '5') {
alert('bagger')
}
else if (count < 5) {
alert('Waardeloos')
}
else if (count > '5') {
alert('Beter')
}
}
This worked for me.
document.getElementsByClassName('content')[0].innerHTML = variable;
Also works.
Related
this is my first question on stackoverflow.
I am learning about javascript and decided to start a project.
I'm making a scoreboard to keep track of the score during table tennis. I managed to make this work and decided to add some features like a match history and show which player has to serve.
However, I'm stuck with the ReferenceError. In most other questions about this, people just forgot to add the variable or it had something to do with jquery. I don't think that's my problem.
In table tennis the player with serve changes every 2 points. I decided to add scorePlayer1 and scorePlayer2 to make a totalScore. When this is divided by 2, I can check if this is an integer, and if it is, the player with serve changes. However, whatever I try, the variable totalScore is not defined.
I learned HTML/CSS first at w3schools.com and later used it to learn javascript.
I have pasted the code into multiple syntax checkers, but got no errors.
The button is there to pick the serve player. Then, I want to swith the right to serve to the opposite player after 2 points are scored. I tried this with function changeServePlayer. However, when I try this in Chrome and type in the console: totalScore, it returns the Uncaught ReferenceError. Why does this happen or is there a better way to achieve the goal?
Here's code I used:
var currentScorePlayerOne = 0;
var currentScorePlayerTwo = 0;
var currentServePlayer;
var totalScore;
window.addEventListener("keyup", checkKeyPress);
function checkKeyPress(key) {
if (key.keyCode == "90" && currentScorePlayerOne != 0) { //Z
document.getElementById('scorePlayerOne').innerHTML = --currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "88") { //X
document.getElementById('scorePlayerOne').innerHTML = ++currentScorePlayerOne;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "78" && currentScorePlayerTwo != 0) { //N
document.getElementById('scorePlayerTwo').innerHTML = --currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
if (key.keyCode == "77") { //M
document.getElementById('scorePlayerTwo').innerHTML = ++currentScorePlayerTwo;
changeServePlayer();
changeServeIcon();
}
updateSet();
}
function updateSet() {
if (currentScorePlayerOne > 10 && currentScorePlayerOne > currentScorePlayerTwo + 1) {
resetScores();
}
if (currentScorePlayerTwo > 10 && currentScorePlayerTwo > currentScorePlayerOne + 1) {
resetScores();
}
}
function resetScores() {
currentScorePlayerOne = 0;
currentScorePlayerTwo = 0;
document.getElementById('scorePlayerOne').innerHTML = currentScorePlayerOne;
document.getElementById('scorePlayerTwo').innerHTML = currentScorePlayerTwo;
}
function changeServePlayer() {
totalScore = currentScorePlayerOne + currentScorePlayerTwo;
Number.isInteger(totalScore / 2);
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 1) {
currentServePlayer = 2;
}
if (Number.isInteger == true && totalScore != 0 && currentServePlayer == 2) {
currentServePlayer = 1;
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
<!DOCTYPE html>
<html>
<head>
<script src="Scoreboard1javascript.js"></script>
</head>
<body>
<button type="button" onclick="chooseServingPlayer()">
Serve
</button>
<script>
var randomServeNumber;
function chooseServingPlayer() {
if (currentScorePlayerOne == 0 && currentScorePlayerTwo == 0) {
document.getElementById('serveP1').style.opacity = "0.2";
document.getElementById('serveP2').style.opacity = "0.2";
randomServeNumber = Math.floor(Math.random() * 10);
if (randomServeNumber > 5) {
currentServePlayer = 1;
changeServeIcon();
} else {
currentServePlayer = 2;
changeServeIcon();
}
}
}
function changeServeIcon() {
if (currentServePlayer == 1) {
document.getElementById('serveP1').style.opacity = "1";
document.getElementById('serveP2').style.opacity = "0.2";
} else {
document.getElementById('serveP2').style.opacity = "1";
document.getElementById('serveP1').style.opacity = "0.2";
}
}
</script>
<nav>
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP1"> Score P1
</nav>
<nav>
Score P2
<img src="tafeltennisbat.png" alt="serve" style="width: 50px; height: 50px; opacity: 0.2" id="serveP2">
</nav>
<nav id="scorePlayerOne" style="font-size: 50px">
0
</nav>
<nav id="scorePlayerTwo" style="font-size: 50px">
0
</nav>
</body>
</html>
I forgot to check which file I was referencing in my html script. I was referencing an old version of the javascript, which made every change I made in javascript useless.
It can be really that stupid sometimes...
I'm creating a simple task where the text shows up after a user clicks the button 3 times. However, the code does not appear to work as I expected.
I've tried adding double bracket inside the if statement as outlined in the MDN guide without luck and also checked similar questions in Stack Overflow like this one, but they're using jquery, so I have no idea how it works.
Here's my codes:
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
}
if (currentval = 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
I'm sure I'm missing something important here and I will be appreciated for your guidance.
if (currentval = 0) { it should be if (currentval == 0) { and your if condition is outside of countDown() function.
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
console.log(currentval);
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!";
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
The errors you made have already been mentioned, I just wanted to add an answer with a little more modern and concise code. You really shouldn't use inline eventlisteners like onclick, instead use HTMLElement.prototype.addEventListener:
countDownBtn.addEventListener('click', () => {
if (Number(countDownBtn.textContent)) {
countDownBtn.textContent -= 1;
}
if (!Number(countDownBtn.textContent)) {
countDownBtn.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>
count = 0
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
if (count < 3) {
count = count+1
}else{
alert("hi")
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
You have missed "=" operator(currentval == 0)
function countDown() {
var currentval = document.getElementById("countDownBtn").innerHTML;
var newval = currentval - 0;
if (currentval > 0) {
newval = currentval - 1;
}
document.getElementById("countDownBtn").innerHTML = newval;
if (currentval == 0) {
document.getElementById("newText").innerHTML = "You clicked 3 times!;"
}
}
<button id="countDownBtn" onclick="countDown()">3</button>
<p id="newText"></p>
Adding to the above answer a more concise code would be:
countDownBtn.addEventListener('click', (e) => {
if (Number(e.target.innerHTML)) {
e.target.innerHTML -= 1;
}else{
e.target.disabled = true;
newText.textContent = "You clicked 3 times!";
}
})
<button id="countDownBtn">3</button>
<p id="newText"></p>
I think so there is a problem with for statement??
Adjusted code again, but not alert popup is all the time even if all the input fields got values?
Hello I am trying to validate a dynamic array of fields on a form:
<form onsubmit="return checkReq();">
<input value="" type="hidden" name="slider[]" id=""/>
</form>
with the following JavaScript, but it doesn't work? Could you tell me please what I am doing wrong.
<script language="javascript">
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
</script>
I think this might help.
function checkReq () {
var boxes = document.getElementsByName("slider[]");
var ret = true;
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
ret = false;
break;
} else {ret = true;}
}
if (ret == false)
{
alert('Problem'); return ret;
}
}
You always return after the first loop, so it doesn't go through each element (and thus redundant), is this intended?
Try this
You are trying to compare element instead of it's value JSFIDDLE
function checkReq () {
var boxes = document.getElementsByName("slider[]");
for (var x = 0; x < boxes.length; x++) {
if(boxes[x].value == '' || boxes[x].value == '0'){
alert('Problem'); return false;
}
else {return true;}
}
}
I am looking to make a checkbox that when unchecked, will turn off a certain function in a .js file. Can someone help me?
popup.html
HTML Check box:
content.js
Turn off this function:
var tweet = new Array();
var tweetName = new Array();
function linkSnipe() {
for (var i = 0; i < 5; i++) {
tweetName[i] = document.getElementsByClassName("fullname js-action-profile-name show-popup-with-id")[0].innerHTML;
tweet[i] = document.getElementsByClassName("js-tweet-text")[i].innerHTML;
}
if (tweet[0].match(shoeName) == shoeName && tweet[0].match(filterer) != filterer && tweet[0].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[0].click();
update();
}
}
else if (tweet[1].match(shoeName) == shoeName && tweet[1].match(filterer) != filterer && tweet[1].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[1].click();
update();
}
}
else if (tweet[2].match(shoeName) == shoeName && tweet[2].match(filterer) != filterer && tweet[2].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[2].click();
update();
}
}
else if (tweet[3].match(shoeName) == shoeName && tweet[3].match(filterer) != filterer && tweet[3].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[3].click();
update();
}
}
else if (tweet[4].match(shoeName) == shoeName && tweet[4].match(filterer) != filterer && tweet[4].match(filter2) != filter2) {
if(checkon == "Tweets"){
document.getElementsByClassName("twitter-timeline-link")[4].click();
update();
}
}
else if(checkon == "Tweets") {
location.reload();
}
}
setTimeout("linkSnipe()", 250);
}
When the checkbox is checked, redefine the function as:
<input type=checkbox ..... onchange="doit()">
function doit() {
window.linkSnipe=function() {}
}
I've used this too:
function doit() {
window['linkSnipe']=function() {}
}
If you want to turn the function on and off by the checkbox:
<input type=checkbox ..... onchange="doit(this)">
var linkSnipeSave = linkSnipe;
function doit(ck) {
if (ck.checked)
window['linkSnipe']=linkSnipeSave
else {
linkSnipeSave = linkSnipe; //not sure if this line is needed...pls test
window['linkSnipe']=function() {}
}
}
You could simply have a Boolean variable that changes with the state of your check box. You could then put an if statement around the function call that will only trigger if the checkbox is checked.
http://jsfiddle.net/W5P8X/
//initialize some variables.
bike_checked = false;
car_checked = false;
//get elements by their ID from html
bike = document.getElementById("bike");
car = document.getElementById("car");
//add event listeners to the html elements we found above
bike.addEventListener("click", toggle_bike, false);
car.addEventListener("click", toggle_car, false);
//toggle bike_checked variable on click
function toggle_bike(){
if(bike_checked == true)
bike_checked = false;
else
bike_checked=true;
current_state();
}
//toggle car_checked variable on click
function toggle_car(){
if(car_checked == true)
car_checked = false;
else
car_checked=true;
current_state();
}
//output current state.
function current_state(){
if(car_checked == true)
alert('Car checked');
if(bike_checked == true)
alert('Bike checked');
}
I answered with only javascript and no jQuery, but you could probably make it a bit more concise with jQuery.
I hope this helps.
I keep getting the following error when I try to insert values by clicking the Next button on values that are already entered in.
Unable to get the value of the property '0': object is null or undefined.
I believe the error is happening at the last value in the array. I indicated the line below with a comment in the code. I want it to get the next value in the array but there isn't one created yet (it gets the next value just fine if the next value is not the last one in the array).
I think that is the reason it's throwing an object null. However, I can't seem to check for the null/undefined and set it using statements such as result[count+1][0] == undefined because it doesn't work! It always throws an error no matter what I do.
Some help would be much appreciated.
Test case:
Insert a value in text box 1 and text box 2
Click Next
Click Previous (in order to edit the values inserted above)
Change the values in the text boxes to something else
Click Next -- error happens
Code:
<html>
<head>
<script type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var result = new Array();
var count = 0;
var input1 = new Array();
var input2 = new Array();
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
</script>
<li>text 1</li>
<input type="text" id="txt1"/>
<br>
<li>text 2</li>
<input type="text" id="txt2"/>
<br>
<input type="button" id="btn" value="next" onclick="move('next')" />
<input type="button" id="btnprevious" value="previous" onclick="move('prev')" />
<br>
<input type="text" id="txtresult"/>
</body>
</html>
You can add a check like this:
if (typeof result[count++] === "undefined") { /* do or do not */ };
Right before:
document.getElementById("txt1").value = result[count++][0];
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
if( result[ ++count ] ) // this checks for undefined
{
document.getElementById("txt1").value = result[count][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count][1];
}
else
{
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count--; // decrement counter
}
}catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
why do you do count++ in these 2 lines?
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
seems like interpreter first increment the count and then try to get item of result which is undefined...
as i undestand pressing previous must "set cursor" to previous vaues so you can change previously entered values... in this case you shouldn't increment counter in these lines.. just remove ++
I don't get why you embedded the arrays three deep. I cleaned up some of the code and made the names more understandable (at least to me).
Regardless, when you were on the last value in the array, count++ didn't exist. Also, don't use count++ as this will increment your count var. Don't use ++ to simplify unless you truly know what you're doing and want to increment. Also, tricky shortcuts will confuse people trying to read your code, so try to be as explicit as possible. (There are exceptions to this statement, as in, you don't need to write for a person who has never coded before)
Here is working javascript:
var result = new Array();
var count = 0;
function move(direction) {
if(direction == 'next') {
var box1 = document.getElementById("txt1").value; //why did you wrap these as arrays?
var box2 = document.getElementById("txt2").value; //
if (result.length == count){
if (box1 == '' || box2 == '') {
alert('you need to put in a value');
} else {
result.push([box1, box2]); //why did you wrap individual numbers in arrays?
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
} else {
try{
result[count][0] = document.getElementById("txt1").value;
result[count][1] = document.getElementById("txt2").value;
if(result[count+1]) { // need this because if on last value in the array, count+1 will not exist yet
document.getElementById("txt1").value = result[count+1][0]; //do not do ++. this will increment count here. don't be tricky with ++
document.getElementById("txt2").value = result[count+1][1]; //because it will confuse others and lead to off by 1 errors
} else {
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
}
catch(err) {
alert(err.description);
}
}
count++;
}
if (direction == 'prev') {
if(count <= 0){
alert("no more elements");
} else {
var prev_val1 = result[count - 1][0];
var prev_val2 = result[count - 1][1];
document.getElementById("txt1").value = prev_val1;
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}