HTML checkbox on/off detection in JavaScript - javascript

I have made a solar system simulation and have some 'settings' which the user can change. I have made it so the settings only update when the save button is pressed. This works and the bodies are hidden if a box is checked but say for example, i checked mercury and saved the changes then wanted to check Venus as well when i save the changes Venus is hidden but Mercury is shown again. how can i make it so that Mercury stays hidden until the box in uncheked.
(note the check boxes decide whether a planet should be hidden or not so hideMer for example when true would stop drawing mercury onto the canvas)
code which i think the issue applies to:
function animate() {
//clears canvas each new loop
if (showPath==false){
c.clearRect(-innerWidth/2,-innerHeight/2,innerWidth,innerHeight);
}
hideBodies = [hideMer, hideVen, hideEar, hideMar, hideJup, hideSat, hideUra, hideNep];
drawSun();
for (var i=0; i< xPosList.length; i++){
leapfrog(i);
if (hideBodies[i]==false){
drawBody(i);
}
}
}
function saveChanges() {
showPath=(document.getElementById("showPath").value=="True");
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (document.getElementById("mer").checked && hideMer == true){
hideMer = false;
}
//Venus
if (document.getElementById("ven").checked && hideVen == false){
hideVen = true;
} else if (document.getElementById("ven").checked && hideVen == true){
hideVen = false;
}
//Earth
if (document.getElementById("ear").checked && hideEar == false){
hideEar = true;
} else if (document.getElementById("ear").checked && hideEar == true){
hideEar = false;
}
//Mars
if (document.getElementById("mar").checked && hideMar == false){
hideMar = true;
} else if (document.getElementById("mar").checked && hideMar == true){
hideMar = false;
}
//Jupiter
if (document.getElementById("jup").checked && hideJup == false){
hideJup = true;
} else if (document.getElementById("jup").checked && hideJup == true){
hideJup = false;
}
//Saturn
if (document.getElementById("sat").checked && hideSat == false){
hideSat = true;
} else if (document.getElementById("sat").checked && hideSat == true){
hideSat = false;
}
//Uranus
if (document.getElementById("ura").checked && hideUra == false){
hideUra = true;
} else if (document.getElementById("ura").checked && hideUra == true){
hideUra = false;
}
//Neptune
if (document.getElementById("nep").checked && hideNep == false){
hideNep = true;
} else if (document.getElementById("nep").checked && hideNep == true){
hideNep = false;
}
console.log(hideMer);
alert(hideMer);
}
whole code: https://jsfiddle.net/nczpod06/6/

In the function save changes for each planet I'm only changing the boolean value when it is checked and not when it is unchecked. To fix this (for example for mercury) I needed to add the not boolean logical operator and then it works... for example:
//Mercury
if (document.getElementById("mer").checked && hideMer == false){
hideMer = true;
} else if (!(document.getElementById("mer").checked) && hideMer == true){
hideMer = false;
}

Related

How to check if switch is true or not to hide the div?

I have some problem when I check the function validation, I need when checking all the cassis is true hide the parent div * errors message *
var error_pass = false;
$('#pass').focusout(function(){
check_pass();
error_pass = false;
if(error_pass !== true){
console.log('its showing!');
}else{
$('.test').fadeOut('522');
}
});
function check_pass() {
var fpass= $('#pass').val();
switch(error_pass = true){
case(fpass.length < 6 ? $('#pass-error-message3').css('color','red'):$('#pass-error-message3').css('color','green') ):
$('#pass-error-message3').show();
case(fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1 ? $('#pass-error-message4').css('color','red') : $('#pass-error-message4').css('color','green')):
$('#pass-error-message4').show();
case(fpass.search(/\d/) == -1 ? $('#pass-error-message2').css('color','red'):$('#pass-error-message2').css('color','green')):
$('#pass-error-message2').show();
default:break;
}
}
Use if else statements like this
function validation() {
var error = false;
if (fpass.length < 6) {
error = true;
$('#pass-error-message3').css('color', 'red').show();
} else {
$('#pass-error-message3').css('color', 'green');
}
if (fpass.search(/(?=.[a-z])(?=.*[A-Z])/) == -1) {
error = true;
$('#pass-error-message4').css('color', 'red').show();
} else {
$('#pass-error-message4').css('color', 'green')
}
if(fpass.search(/\d/) == -1){
error = true;
$('#pass-error-message2').css('color','red').show();
}else{
$('#pass-error-message2').css('color','green');
}
if(error === false){
hideParentDiv(); // Here hide the div
}
}
Much cleaner approach

Tell Unity that an Axis isn't being pressed when it is

Hello fellow programmers.
I'm here to ask you a very unusual question. I have created a game and in it when you hit a wall you bounce back but if you are still holding the key to go the direction you were going when you hit it it will just stay still, so I need to tell Unity that an Axis isn't being used anymore, is there a way to do this? Please note that I am using JavaScript and I am aware that it will be removed from Unity and that C# is better so don't comment that I should write code in C# please.
Code--
The movement:
if(Input.GetAxis("Forward") && isMovingBackward == false) {
if(lastDir == "backward") {
deaccelerate();
brake();
braking = true;
canRotLeft = false;
canRotRight = false;
} if(!(lastDir == "backward") && canMoveForw == true) {
accelerate();
isMoving = true;
isMovingForward = true;
isMovingBackward = false;
canRotLeft = true;
canRotRight = true;
lastDirForw();
transform.Translate(Vector3(1, 0, 0) * speed * Time.deltaTime);
}
}
if(!(Input.GetAxis("Forward"))) {
isMovingForward = false;
}
if(!(Input.GetAxis("Backward"))) {
isMovingBackward = false;
}
if(Input.GetAxis("Backward") && isMovingForward == false) {
if(lastDir == "forward") {
deaccelerate();
brake();
braking = true;
canRotLeft = false;
canRotRight = false;
} if(!(lastDir == "forward") && canMoveBack == true) {
accelerate();
isMoving = true;
isMovingBackward = true;
ifMovingForward = false;
breakingBack = false;
canRotLeft = true;
canRotRight = true;
lastDirBack();
transform.Translate(Vector3(1, 0, 0) * -speed * Time.deltaTime);
}
}
The lastDir functions:
function lastDirForw() {
if(collided == true) {
brake();
canMoveBack = false;
lastDir = "backward";
} else {
canMoveBack = true;
lastDir = "forward";
}
}
function lastDirBack() {
if(collided == true) {
brake();
canMoveForw = false;
lastDir = "forward";
} else {
canMoveForw = true;
lastDir = "backward";
}
}

Form which redirects by achieved score

I have a html form that has 16 questions that have radio buttons to answer "Yes or No" each having a different value, after q16 the user clicks next and depending on the score the user is taken to the right page ! of 3 pages
Here is the code that I have done was working upto q9 but cannot see where I have gone wrong
function submitForm(){
var totalScore = 0;
if(document.myform.username.value.length == 0){ //make sure a name has been entered
alert('Please enter a name.');
}else if(document.myform.q1[0].checked == false && document.myform.q1[1].checked == false){// make sure q1 has been answered
alert('Please answer question 1.');
}else if(document.myform.q2[0].checked == false && document.myform.q2[1].checked == false){// make sure q2 has been answered
alert('Please answer question 2.');
}else if(document.myform.q3[0].checked == false && document.myform.q3[1].checked == false){// make sure q3 has been answered
alert('Please answer question 3.');
}else if(document.myform.q4[0].checked == false && document.myform.q4[1].checked == false){// make sure q4 has been answered
alert('Please answer question 4.');
}else if(document.myform.q5[0].checked == false && document.myform.q5[1].checked == false){// make sure q5 has been answered
alert('Please answer question 5.');
}else if(document.myform.q6[0].checked == false && document.myform.q6[1].checked == false){// make sure q6 has been answered
alert('Please answer question 6.');
}else if(document.myform.q7[0].checked == false && document.myform.q7[1].checked == false){// make sure q7 has been answered
alert('Please answer question 7.');
}else if(document.myform.q8[0].checked == false && document.myform.q8[1].checked == false){// make sure q8 has been answered
alert('Please answer question 8.');
}else if(document.myform.q9[0].checked == false && document.myform.q9[1].checked == false && document.myform.q9[2].checked == false){// make sure q9 has been answered
alert('Please answer question 9.');
}else if(document.myform.q10[0].checked == false && document.myform.q10[1].checked == false && document.myform.q10[2].checked == false){// make sure q10 has been answered
alert('Please answer question 10.');
}else if(document.myform.q11[0].checked == false && document.myform.q11[1].checked == false){// make sure q11 has been answered
alert('Please answer question 11.');
}else if(document.myform.q12[0].checked == false && document.myform.q12[1].checked == false){// make sure q12 has been answered
alert('Please answer question 12.');
}else if(document.myform.q13[0].checked == false && document.myform.q13[1].checked == false){// make sure q13 has been answered
alert('Please answer question 13.');
}else if(document.myform.q14[0].checked == false && document.myform.q14[1].checked == false){// make sure q14 has been answered
alert('Please answer question 14.');
}else if(document.myform.q15[0].checked == false && document.myform.q15[1].checked == false && document.myform.q15[2].checked == false){// make sure q15 has been answered
alert('Please answer question 15.');
}else if(document.myform.q16[0].checked == false && document.myform.q16[1].checked == false && document.myform.q16[2].checked == false){// make sure q16 has been answered
alert('Please answer question 16.');
}else{ //everything has been entered
var q1Score = 0 //work out the value of q1
if(document.myform.q1[0].checked == true){
q1Score=document.myform.q1[0].value;
}else if(document.myform.q1[1].checked == true){
q1Score=document.myform.q1[1].value;
}
var q2Score = 0 //work out the value of q2
if(document.myform.q2[0].checked == true){
q2Score=document.myform.q2[0].value;
}else if(document.myform.q2[1].checked == true){
q2Score=document.myform.q2[1].value;
}
var q3Score = 0 //work out the value of q3
if(document.myform.q3[0].checked == true){
q3Score=document.myform.q3[0].value;
}else if(document.myform.q3[1].checked == true){
q3Score=document.myform.q3[1].value;
}
var q4Score = 0 //work out the value of q4
if(document.myform.q4[0].checked == true){
q4Score=document.myform.q4[0].value;
}else if(document.myform.q4[1].checked == true){
q4Score=document.myform.q4[1].value;
}
var q5Score = 0 //work out the value of q5
if(document.myform.q5[0].checked == true){
q5Score=document.myform.q5[0].value;
}else if(document.myform.q5[1].checked == true){
q5Score=document.myform.q5[1].value;
}
var q6Score = 0 //work out the value of q6
if(document.myform.q6[0].checked == true){
q6Score=document.myform.q6[0].value;
}else if(document.myform.q6[1].checked == true){
q6Score=document.myform.q6[1].value;
}
var q7Score = 0 //work out the value of q7
if(document.myform.q7[0].checked == true){
q7Score=document.myform.q7[0].value;
}else if(document.myform.q7[1].checked == true){
q7Score=document.myform.q7[1].value;
}
var q8Score = 0 //work out the value of q8
if(document.myform.q8[0].checked == true){
q8Score=document.myform.q8[0].value;
}else if(document.myform.q8[1].checked == true){
q8Score=document.myform.q8[1].value;
}
var q9Score = 0 //work out the value of q9
if(document.myform.q9[0].checked == true){
q9Score=document.myform.q9[0].value;
}else if(document.myform.q9[1].checked == true){
q9Score=document.myform.q9[1].value;
}else if(document.myform.q9[2].checked == true){
q9Score=document.myform.q9[2].value;
}
var q10Score = 0 //work out the value of q10
if(document.myform.q10[0].checked == true){
q10Score=document.myform.q10[0].value;
}else if(document.myform.q10[1].checked == true){
q10Score=document.myform.q10[1].value;
}else if(document.myform.q10[2].checked == true){
q10Score=document.myform.q10[2].value;
}
var q11Score = 0 //work out the value of q11
if(document.myform.q11[0].checked == true){
q11Score=document.myform.q11[0].value;
}else if(document.myform.q11[1].checked == true){
q11Score=document.myform.q11[1].value;
}
var q12Score = 0 //work out the value of q12
if(document.myform.q12[0].checked == true){
q12Score=document.myform.q12[0].value;
}else if(document.myform.q12[1].checked == true){
q12Score=document.myform.q12[1].value;
}
var q13Score = 0 //work out the value of q13
if(document.myform.q13[0].checked == true){
q13Score=document.myform.q13[0].value;
}else if(document.myform.q13[1].checked == true){
q13Score=document.myform.q13[1].value;
}
var q14Score = 0 //work out the value of q14
if(document.myform.q14[0].checked == true){
q14Score=document.myform.q14[0].value;
}else if(document.myform.q14[1].checked == true){
q14Score=document.myform.q14[1].value;
}
var q15Score = 0 //work out the value of q15
if(document.myform.q15[0].checked == true){
q15Score=document.myform.q15[0].value;
}else if(document.myform.q15[1].checked == true){
q15Score=document.myform.q15[1].value;
}else if(document.myform.q15[2].checked == true){
q15Score=document.myform.q15[2].value;
}
var q16Score = 0 //work out the value of q16
if(document.myform.q16[0].checked == true){
q16Score=document.myform.q16[0].value;
}else if(document.myform.q16[1].checked == true){
q16Score=document.myform.q16[1].value;
}else if(document.myform.q16[2].checked == true){
q16Score=document.myform.q16[2].value;
}
//add the scores together
totalScore=parseInt(q1Score)+parseInt(q2Score)+parseInt(q3Score)+parseInt(q4Score)+parseInt(q5Score)+parseInt(q6Score)+parseInt(q7Score)+parseInt(q8Score)+parseInt(q9Score)+parseInt(q10Score)+parseInt(q11Score)+parseInt(q12Scorce)+parseInt(q13Score)+parseInt(q14Score)+parseInt(q15Score)+parseInt(q16Score);
if(totalScore<=15){ //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else if (totalScore >=16 && totalScore <30){ //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}
}
To avoid this kind of repetitive code, you might want to use loops as Bergi pointed out in his comment. You could do something like this for example: (NOTE - untested!)
function submitForm() {
if(document.myform.username.value.length == 0) { //make sure a name has been entered
alert('Please enter a name.');
return;
}
var totalScore = 0;
var threeAnswerQuestions = [9, 10, 15, 16];
var numberOfQuestions = 16;
for(var i = 1; i <= numberOfQuestions; i++) {
var numerOfAnswers = threeAnswerQuestions.indexOf(i) != -1 ? 3 : 2;
var answerChecked = false;
for(var j = 0; j < numerOfAnswers; j++) {
if(document.myform['q'+i][j].checked) {
answerChecked = true;
totalScore += parseInt(document.myform['q'+i][j].value);
break;
}
}
if(!answerChecked) {
alert('Please answer question ' + i + '.');
return;
}
}
if(totalScore <= 15) { //if it's less than or equal to 15 go to this page...
window.location.href='greenzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else if (totalScore >= 16 && totalScore < 30) { //go to this page
window.location.href='yellowzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
} else {
window.location.href='redzonePage.html?name='+document.myform.username.value+'&score='+totalScore;
}
}

Checkbox in HTML turns off a function in a .js file

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.

Radio button validation causing rest of validation to fail

The radio validation works but then the rest don't. What have I done wrong?
function validateRadio(radios) {
for (i = 0; i < radios.length; ++i) {
if (radios[i].checked) return true;
}
return false;
}
function validateForm() {
if (validateRadio(document.forms["pancettaForm"]["updateShip"])) {
return true;
} else {
alert("Please tell us how you would like to update your order.");
return false;
}
}
var x = document.forms["pancettaForm"]["order-number"].value;
if (x == null || x == "") {
alert("Please provide your order number.");
return false;
}
var x = document.forms["pancettaForm"]["full-name"].value;
if (x == null || x == "") {
alert("Please provide your full name, or the recipients name if you are updating shipping information.");
return false;
}
var x = document.forms["pancettaForm"]["phone"].value;
if (x == null || x == "") {
alert("Please provide a phone number in case of delivery questions.");
return false;
}
var display = document.getElementById('address').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["address"].value;
if (x == null || x == "") {
alert("Please provide your address.");
return false;
}
}
var display = document.getElementById('city').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["city"].value;
if (x == null || x == "") {
alert("Please provide your city.");
return false;
}
}
var display = document.getElementById('state').style.display;
if (display == 'block') {
if (document.pancettaForm.state.value == "- Select State -") {
alert("Please provide your state.");
return false;
}
}
var display = document.getElementById('zip').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["zip"].value;
if (x == null || x == "") {
alert("Please provide your zip code.");
return false;
}
}
var display = document.getElementById('newShipDate').style.display;
if (display == 'block') {
if (document.pancettaForm.state.value == "- Select Date -") {
alert("Please choose your new shipping date.");
return false;
}
}
Just reverse the test so you do not have to return
if(!validateRadio (document.forms["pancettaForm"]["updateShip"]))
{
alert("Please tell us how you would like to update your order.");
return false;
}
// continue
You had the end bracket after the test of the radios so the rest of the script just floated in cyberspace
Also return true only once at the end and do not have var x multiple times and be consistent in how you access the form elements and I also fixed your date test which was testing state
function validateForm() {
var x,display,form = document.forms["pancettaForm"];
if (!validateRadio(form["updateShip"])) {
alert("Please tell us how you would like to update your order.");
return false;
}
x = form["order-number"].value;
if (x == null || x == "") {
alert("Please provide your order number.");
return false;
}
x = form["full-name"].value;
if (x == null || x == "") {
alert("Please provide your full name, or the recipients name if you are updating shipping information.");
return false;
}
x = form["phone"].value;
if (x == null || x == "") {
alert("Please provide a phone number in case of delivery questions.");
return false;
}
display = form["address"].style.display;
if (display == 'block') {
x = form["address"].value;
if (x == null || x == "") {
alert("Please provide your address.");
return false;
}
}
display = form["city"].style.display;
if (display == 'block') {
x = form["city"].value;
if (x == null || x == "") {
alert("Please provide your city.");
return false;
}
}
display = form['state'].style.display;
if (display == 'block') {
x = form['state'].value;
if (x == "- Select State -") {
alert("Please provide your state.");
return false;
}
}
display = form['zip'].style.display;
if (display == 'block') {
x = form["zip"].value;
if (x == null || x == "") {
alert("Please provide your zip code.");
return false;
}
}
display = form["newShipDate"].style.display;
if (display == 'block') {
x = form["newShipDate"].value;
if (x.value == "- Select Date -") {
alert("Please choose your new shipping date.");
return false;
}
}
return true;
}

Categories