I would like to run different functions depending if a field is checked or not during page load.
So I use window.onload. The first if condition works great but I would like to add more if conditions as defined below. But it doesn't seem to be the proper way.
I thought I could work with if and if else. Does someone know how to make multiple if conditions work for window.onload function?
<script>
window.onload=function(){
if (document.getElementById("field1").checked) {
document.getElementById("field2").style.color = "red";
}
else if (document.getElementById("field3").checked) {
document.getElementById("field4").style.color = "red";
}
<script>
Added: I would like to add that all functions must be executed if all the if statements are fitting (so if else functions are maybe incorrect in this context). If only field1 is fitting the conditions, only the matching field2 should turn colour of text into red.
It’s not about the colour (that’s just an example for a JS function) - in real I want 3 things: enter value X, turn red and get disabled for future inputs (I already coded that - so not necessary).
UPDATE: Thanks to your comments. I used the code of Emiel Zuurbier: It's working for field 1 until 4 but not for field 10 until 14, did I wrote it wrong?
<script>
const fieldMap = [
['field1', 'field2', 'field3', 'field4'],
['field10', 'field11', 'field12', 'field14']
];
window.onload = function() {
for (const [fieldA, fieldB, fieldC, fieldD] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).value = "X";
document.getElementById(fieldB).style.color = "red";
document.getElementById(fieldB).disabled = true;
document.getElementById(fieldC).value = "X";
document.getElementById(fieldC).style.color = "red";
document.getElementById(fieldC).disabled = true;
document.getElementById(fieldD).value = "X";
document.getElementById(fieldD).style.color = "red";
document.getElementById(fieldD).disabled = true;
}
}
}
</script>
You can eleminate repeating tasks by taking the dynamic parts of your code, in this case your ID selectors, and put them in an array (or object) which you can loop over.
const fieldMap = [
['field1', 'field2'],
['field3', 'field4']
];
window.onload = function() {
for (const [fieldA, fieldB] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).style.color = 'red';
}
}
}
The principle of writing your code like this is called DRY (Don't Repeat Yourself)
winow.onload executes your function() when the page is fully loaded, but it happens just once. If the code you provided is correct then I think you might be missing } at the end. However, there's still one thing that bothers me. If you check if a specified checkbox is checked it checks the checked property only when the page is fully loaded, not when the user clicks on the #field checkbox. If you want the check whether the user checked the checkbox then you can use eventlistener 'check'.
Related
I"m pretty sure I'm doing something wrong in the code, as to why it's not functioning the way I want it. Firstly, here's the code:
function onEdit(a) {
var sheet = a.source.getActiveSheet();
var aa = SpreadsheetApp.getActiveSpreadsheet();
var COMP = aa.getSheetByName("COMP");
var COMPcell = sheet.getRange('B6').getValue();
if(COMPcell = 'TRUE'){COMP.showSheet();}else{COMP.hideSheet();}
}
In here, I have a checkbox on cell B6 of the 'active sheet' (named Monthly summary). When checked (and thus have a value of TRUE), I want the sheet named "COMP" to appear. Otherwise, it should be hidden. I'm not really good at coding and I've researched the above formula and modified it as to my requirement, but I can't get it to work.
Any insights on this will be very much appreciated. Thanks!
You want to show the sheet of COMP only when the checkbox of "B6" is checked.
You want to hide the sheet of COMP when the checkbox of "B6" is not checked.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modified script 1:
If your script is modified, in your script, COMPcell = 'TRUE' of the if statement is not compared the value. In this case, please modify to COMPcell === true. The modified script reflected this is as follows.
function onEdit(a) {
var sheet = a.source.getActiveSheet();
var aa = SpreadsheetApp.getActiveSpreadsheet();
var COMP = aa.getSheetByName("COMP");
var COMPcell = sheet.getRange('B6').getValue();
if (COMPcell === true) { // Modified
COMP.showSheet();
} else {
COMP.hideSheet();
}
}
Modified script 2:
When the event object and isChecked() are used, your script can also be modified as follows. In this script, only when the checkbox of "B6" is edited, the script works.
function onEdit(a) {
var range = a.range;
if (range.getA1Notation() == "B6") {
var COMP = a.source.getSheetByName("COMP");
if (range.isChecked()) {
COMP.showSheet();
} else {
COMP.hideSheet();
}
}
}
References:
if...else
isChecked()
Event Objects
I am trying to make a Contact form with Radio Buttons and Checkboxes for Packages I intend to offer. The first Radio is for the full Package. The Second Radio Button reveals the Checkboxes that breaks the full package into single options.
What I am trying to achieve is when all checkboxes get checked, the first radio gets checked and all checkboxes get unchecked and are hidden. I managed to get the function to work with one little
var radio1 = document.getElementbyID('radio1');
var radio2 = document.getElementbyID('radio2');
var checkgroup = document.getElementbyID('checkgroup');
var check1 = document.getElementbyID('check1');
var check2 = document.getElementbyID('check2');
var check3 = document.getElementbyID('check3');
var check4 = document.getElementbyID('check4');
$(document).change(function () {
if (radio2.checked) {
checkgroup.style.display = "block";
} else {
checkgroup.style.display = "none";
}
});
$(document).change(function () {
if ((check1&&check2&&check3&&check4).checked) {
check1.checked = false;
check2.checked = false;
check3.checked = false;
check4.checked = false;
checkgroup.style.display = "none";
radio1.checked = true;
}
});
Whenever I check the the checkbox that is last in the if() condition (only the last, not the others) it executes the function which misses the point.
My Goal:
If all get Checked, Execute the Function (Uncheck all, Hide the Checkboxes, Switch back to Radio1). If any 3 get checked nothing should happen.
I feel like i'm missing something, I just don't know what.
Change if ((check1&&check2&&check3&&check4).checked)
to if (check1.checked && check2.checked && check3.checked && check4.checked)
I'm confused that it even worked somewhat since you essentially used && between Javascript objects and not (boolean) variables
Try this: https://jsfiddle.net/h95y86gt/22/
Also, I hope getElementbyID is a typo for document.getElementById()
So what I'm trying to do is basically check if the response from the server contains alternatives. If it does then it should print the alternatives out , hide the text area where I would answer the question if the question did not contain alternatives and show the radio buttons. Problem is, it prints out the response, but never hides/shows the text area or the radio buttons.
I tried putting the code for the visibility in a button to see if it works on click, and it does, but it does not work when I put the same code in the if statement.
Also, another problem is that instead of printing out the actual alternatives, it just prints out Object object, but when I try to print out the question, it prints it out correctly.
HideAllRadios and ShowArea functions are basically the same as what's in the if statement, but reversed.
Here is the code:
QuestionReq.onreadystatechange = function(){
if(QuestionReq.readyState === 4 && QuestionReq.status === 200) {
response = JSON.parse(QuestionReq.responseText);
console.log(response);
questionLink.innerText = response.question;
url = response.nextURL;
// questAltLink.innerText = response.alternatives;
if(response.alternatives !=null){
questAltLink.innerText = response.alternatives;
AnswerArea.style.visibility = "hidden";
RadioArea.style.visibility = "visible";
}
HideAllRadios();
ShowArea();
}
Here is how they are declared:
var questions = function () {
var AnswerArea = document.getElementById("AnswerArea");
var RadioArea = document.getElementById("radioplace");
I am learning javascript and I have a problem with changeimage function.
I need to change both one, and second image.
Here is jsfiddle.
https://jsfiddle.net/7ewjoxnv/1/
And here below, javascript:
var switchingImage;
function changeImage()
{
switchingImage.src = this.value;
}
window.onload = function() {
var radios = document.getElementById('imageSwitcher').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch');
for(var i=0;i<radios.length;i++)
{
radios[i].onclick = changeImage;
}
var radios = document.getElementById('imageSwitcher2').getElementsByTagName('input');
switchingImage = document.getElementById('imageToSwitch2');
for(var o=0;o<radios.length;o++)
{
radios[o].onclick = changeImage;
}
}
Any help will be much appreciated.
Best Regards,
David!
When you do var radio = and switchingImage = for the second time, you are changing their previous values.
In the case of radios it just happens and does not affect you because you have already applied the listeners you wanted to the old radio buttons.
In the case of switchingImage however, it affects you, because switchingImage will ultimately point to the document.getElementById('imageToSwitch2'). So when you call changeImage() it will always operate on document.getElementById('imageToSwitch2').
Here's one way you could solve your problem. It is purposefully not the best solution. Use it as a baseline to improve on it.
https://jsfiddle.net/7ewjoxnv/4/
I am unrehearsed in javascript and was hoping for some help with a next button that links to an id based on the array. Here is the array
var baseline_next=new Array();
baseline_next[0]="#one";
baseline_next[1]="#two";
baseline_next[2]="#three";
baseline_next[3]="#four";
baseline_next[4]="#five";
baseline_next[5]="#six";
baseline_next[6]="#six2";
baseline_next[7]="#seven";
baseline_next[8]="#eight";
baseline_next[9]="#nine";
baseline_next[10]="#ten";
baseline_next[11]="#eleven";
baseline_next[13]="#thirteen";
baseline_next[14]="#fourteen";
baseline_next[15]="#fifteen";
baseline_next[16]="#sixteen";
baseline_next[17]="#seventeen";
baseline_next[18]="#eighteen";
baseline_next[19]="#nineteen";
baseline_next[20]="#twenty";
baseline_next[21]="#twentyone";
baseline_next[22]="#twentytwo";
baseline_next[22]="#twentythree";
Basically what I need is, when the next button is clicked first ("0" ~ #one) I need the next buttons id to become two, and when clicked again it needs to become #three. I have no idea how to link an array to a button. The reason I need this to happen is because I am using ajax to .load div contents, so the next button doesn't actually submit, it just becomes a new next button. I dont know if it matters, but here is a part of what the button would cause to happen on click.
$('#one').click(function(){
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area");
$("#area").show("slide", { direction: "right" }, 500);
$("#two").show();
});
$('#two').click(function(){
if((document.form1.baseline_01[0].checked || document.form1.baseline_01[1].checked| document.form1.baseline_01[2].checked)
&& (document.form1.baseline_02[0].checked || document.form1.baseline_02[1].checked)
&& (document.form1.baseline_03_native.checked || document.form1.baseline_03_asian.checked|| document.form1.baseline_03_black.checked|| document.form1.baseline_03_pacific.checked|| document.form1.baseline_03_white.checked|| document.form1.baseline_03_other.checked)){
if(document.form1.baseline_03_other.checked && document.form1.baseline_03_other_text.value==""){
alert("Please fill in what other race you concider yourself to be.");
return false;
}else{
$("#area").hide("slide", { direction: "left" }, 500);
$("#area").load("test_it.jsp #area2");
$("#area").show("slide", { direction: "right" }, 500);
$("#three").show();
return true;
}
}else{
alert("Please select an answer for each question.");
return false;
}
});
I must apologize in advanced if my question is hard to follow, I just started coding this year.
I think that you should consider reworking your code a bit to not have this list of IDs and use a single class on all of the elements. It would help to see how your HTML is set up to get the next element based on class as well.
Since you already have this array of doom, though, I guess we'll have to use it. Ideally, you have the same class on each element. Let's say, .number.
$(".number").on('click', function () {
var nextID = baseline_next.indexOf(this.id) + 1;
});
If you can't use .number, then you can do the same thing except with a list of every ID that needs to be bound .. ouch. In the above function, nextID should be the index of the ID that comes after the clicked element.
By the way, IDs can be numbers, and you could even use data-id that contains the number. That would be easier too.
OK I really need to ask why are you doing this, are you sure that creating more than 20 ID's called like that is the better way to do want you want?
Anyways, first of all, you can create the array in a shorthand way:
var baseline_next= ["#one", "#two", "#four", "#five", "#six", "#six2" ..., "#twentythree";
(btw "#six2"? really?)
then do something like this:
var counter = 0; // start for the first one
$("#button").on('click', function () {
var id = counter++;
baseline[id]; // and I don't know what you want to do with this, but here it is!
});
Ancient question. (7 years wowzers). Here is some logic that I used for determining the next item in an array using indexOf. This will also start from the beginning once you reach the end of your array.
let options = [true,false,null];
let current = options.indexOf(this.get('order'));
let next = (current+1 > options.length-1 ? 0 : current+1);
this.set('order', options[next]);
It can be simplified as follows:
let baseline_next = ["#one", "#two", "#three"];
Don't use a var as it behaves unpredictably.
Add a variable count to change the index of the array.
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$(baseline_next[count]).click(function() {
count++;
});
Or
let count = 0;
let baseline_next = ["#one", "#two", "#three"];
$("#one").click(function() {
$(baseline_next[count]).click();
count++;
});