Change table depending on radiobutton selection - javascript

I have two different datasets of worldcupresults from 2006 and 2010. I want to be able to select the 2006 radiobutton and display the results for that year in
a table, i also want to select 2010 and show those results for that year in a table.
The 2006 table displays correctly but when the 2010 radiobutton is selected, nothing happens. Any help is appreciated.
This is the code that I have tried but it is not working successfully.
if(document.getElementById("radiobutton2006").checked = true)
{
$ ('#table2006').append(`<tr><td>${value.team}</td <td>${value.result}</td></tr>`);
}
else if(document.getElementById("radiobutton2010").checked = true)
{
$ ('#table2010').append(`<tr><td>${value.team}</td> <td>${value.result}</td></tr>`);
}

The if statement requires the specified condition to be either truthy or falsy. You are using assignment operator = in your if-else condition. The = sign isn't really necessary as checked is a boolean property.
if(document.getElementById("radiobutton2006").checked)
{
$ ('#table2006').append(`<tr><td>${value.team}</td <td>${value.result}</td></tr>`);
}
else if(document.getElementById("radiobutton2010").checked)
{
$ ('#table2010').append(`<tr><td>${value.team}</td> <td>${value.result}</td></tr>`);
}
But if you want to continue with equality operator, you should replace = with == or ===. Note that == and === are not same. === also checks for the type.

Just wanted to build on Elishs' answer a bit. You appear to be using jQuery, so I updated the document.getElementById appropriately.
Also, as mentioned by Elish, there are two forms of equality in JavaScript. == is weak equality, and === is strict. You should generally use strict, because there are situations where == can cause unexpected behavior.
if ($("#radiobutton2006").prop('checked') === true)
See:
JavaScript - The Good Parts
JQuery - Prop

Related

Using 2 conditions with an IF statement in Cypress

Hello I'm trying to run the following code but somehow it does not work. The same code will work if I simply separate the IF statement in 2 and nest it.
My intention is to select only one element from the dropdown list but buy using includes, I'm getting 2 results; that is why I was trying to add an extra condition to it.
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands" && $el.text().length === 11)) {
cy.wrap($el).click();
}
Do you happen to know why that is? is there a better way of doing this? thank you
You could do it with a .filter() with a function parameter.
This variation is not currently in the Cypress docs, but they are using jQuery under the hood so refer here jQuery docs, filter(function).
Note the function receives the raw DOM element so use innerText instead of jQuery .text().
You can add multiple criteria, but with === it checks for an exact match and the length check isn't needed.
cy.get("#autocomplete").type("ne");
cy.get('.ui-menu-item') // all items
.filter((index, el) => el.innerText === "Netherlands") // precise match
.eq(0) // take the first
.click(); // select it
There is a ) missing after the text Netherlands, you have to add that and there is an extra bracket ) added after 11, you have to remove that. So, your code should be:
cy.get("#autocomplete").type("ne");
cy.get(".ui-menu-item").each(($el) => {
if ($el.text().includes("Netherlands") && $el.text().length === 11) {
cy.wrap($el).click();
}
I had a somewhat similar issue where I want to select an item in a custom select component (so not a native select element).
I used a derivation of the most upvoted answer to achieve this:
cy.get('my-component .ng-dropdown-panel .ng-option')
.filter((_, el) => {
return el.querySelector('span.badge-location')?.textContent === locationName
&& el.querySelector('span.platform-name')?.textContent === platformName;
})
.should('have.length', 1)
.click();
The code loops through all possible option elements and finds the one I'm looking for and clicks on that one.

How do you compare two variables in Javascript?

I am trying to compare two different variables with each other and execute certain code if they match.
The variables are: userInput and commandOne
Firstly, a button is pressed to call myTest().
function myTest() {
userInput = document.getElementById("runBox").value;
testInput();
}
The function gathers text from an input box on my page and stores it in a variable named userInput. It then calls my next function...
function testInput() {
if (userInput = commandOne) {
document.getElementById("demo").innerHTML += "<br>executed!";
}else {
alert("this is an alert message");
}
}
This part is designed to test if userInput matches the variable named commandOne. (commandOne's value is currently set to "ip").
If it does match, it will add text (executed!) to a paragraph with the "demo" ID. If it does not match, it will alert the user in an alert box.
My problem is that the variables do not seem to be comparing. No matter what the user puts into userInput the text (executed!) is always outputted to my paragraph. It appears that the browser thinks they are matching when they are not.
You missed your operator in the if statement.
if (userInput == commandOne)
== compares value
if (userInput === commandOne)
=== compares values and data types.
You had used the wrong operator. You must use == sign instead of a single = sign.
function testInput() {
if (userInput == commandOne) {
document.getElementById("demo").innerHTML += "<br />executed!";
} else {
alert("This is an alert message");
}
}
A single = sign (=) means that the value on the left side of the sign gets the same value as on the right side of the sign.
Double= sign (==) means that two values on the each side of the sign are equal.
Triple = sign (===) means that both the values are equal and of the same type.
Click here for more information.
As mentioned - you have the wrong operator - however i just wanted to show an alternative to the logic: - the ternary operator - makes it much nicer and cleaner to read and reduces the if / else markup.
Incidentally - given the code provided - you don't even need to call teh second function - the entire thing can be done in one function. Also - if the alert is purely to demonstrate the "else" outcome - you should investigae the use of the console.log() - its bettter for debugging.
To explain the ternary operator - the condition to be met is written first (note that there is no "if" preceding it. Following it - use the "?" charcter to give an action if hte comparison is true and use a ":" character for if the outcome is false.
Note that I always write the ternary operators on the three lines as i have done here - I find it easier to read - it can all be written on one line - personal preference.
And last thing - no ";" at the end of the "true" portion of the statemtn - it is all one expression that I happen to have written over three lines.
function testInput() {
userInput == commandOne
? document.getElementById("demo").innerHTML += "<br>executed!"
: alert("this is an alert message");
}

Syntax for an onChange event

I have an Adobe Acrobat form and I use a small java script to obscure certain areas of the form based on selections in other fields.
if (event.value = "No") {
event.target.fillColor = color.white ;
} else {
event.target.fillColor = color.transparent ;
}
This works ok for me the first time I make a selection but once I select "No" for the first time it doesn't matter if I go in and change my selection, the backgrounds stay white.
I've been told I need to add an onChange event but I have no idea where to start.
Any help will be appreciated.
In JavaScript, = assigns to a value, and == compares against that value, without assigning.
Let's look at the following code:
if (event.value = "No") { }
It works the first time because it assigns event.value to No (regardless of what it was before), and the assignment is successful, so the condition evaluates to true.
It then subsequently succeeds every time for the same reason.
To fix this, you're looking for if (event.value == "No") { }, or the stricter if (event.value === "No") { }, which also checks that event.value matches the type of No.
=== is really important when dealing with numbers, because in JavaScript, a string representation of 1 is not the same thing as an integer representation of 1:
console.log("1" == 1);
console.log("1" === 1);
console.log("1" + 1);
console.log(1 + 1);
Hope this helps! :)

Script to automatically capitalize contents of a cell in Google Sheets?

I have a spreadsheet that takes input of stock symbols. I would like them to always be in ALL CAPS regardless of how they are typed in. This appears to require some scripting as there is no way to do this with a function unless a second copy of the column exists, which is not acceptable.
I have a solution which works, with one critical problem. The code is as follows:
function OnEdit(e) {
var ss = e.source.getActiveSheet(),
sheets = ['Trades', ''],
ind = sheets.indexOf(ss.getName());
if (ind === 0 && e.range.rowStart > 1 && e.range.columnStart >= 1 ) {
e.range.setValue(e.value.toUpperCase());
}
}
It works great, and allows me to add as many tabs and columns to format as I wish. Unfortunately it also capitalizes the FORMULAS inside the cells, which is breaking formulas that use the importhtml() function, because it capitalizes the URL being requested.
So, anyone know a way to do exactly what the above code does, but not touch the actual formulas inside the cells, only the text that they output?
EDIT: Thanks to #ocordova's comment, I thought I had something that would do the job well enough. Unfortunately it's behaving strangely... it works partly o some columns, and not at all on others. Here is my current code (slightly altered from earlier for clarity):
function onEdit(e){
var activeSheet = e.source.getActiveSheet(),
sheets = ['NEW Trades', ''],
sheetIndex = sheets.indexOf(activeSheet.getName());
if (sheetIndex === 0 && e.range.rowStart > 1 && e.range.columnStart >0 && e.range.getFormula() == '') {
e.range.setValue(e.value.toUpperCase());
}
}
Anyone have any ideas why some cells in some columns will capitalize as expected, and other cells in those same columns won't, and yet other columns won't capitalize at all, anywhere?
EDIT 2: My trouble appears to be related to, or a conflict with, Data Validation. The columns I'm trying to capitalize are fed by lists of values on another sheet. If the value was present previously in lower case, and then I applied the data validation to the column, the script will not capitalize the value. However if I select the appropriate, capitalized selection from the data validation list, and then re-type the same value in lower case, the script DOES kick in and capitalize. Very strange and confusing. I could be wrong about the conflict, but that's what it seems like to me.
EDIT 3: It's not related to data validation, because it's behaving the same way on a simple column that has no validation at all. If the value I had previously entered was already in lowercase, then typing it again in lowercase will not activate the script. BUT if I type the value in CAPS, then re-type it in lowercase, the script capitalizes it. Maybe some strange condition relating to when the script is triggered...?
If you don't want to capitalize if the cell contains a formula, you can use the method getFormula() and check if the cell contains a formula.
Returns the formula (A1 notation) for the top-left cell of the range, or an empty string if the cell is empty or doesn't contain a formula.
The code should look like this:
if (ind === 0 && e.range.rowStart > 1 && e.range.columnStart >= 1 && e.range.getFormula() == '') {
e.range.setValue(e.value.toUpperCase());
}
EDIT:
If I've understood you correctly, you're typing exactly the same value, example: if the value in the cell is México, and you delete all or some characters and inmediately type México again, in that scenario the old value and the new value are the same and the OnEdit() won't be fired. Another example is if you change the format of the value, that's another type of event.
If you want know how the event is considered, you can use an installable on change trigger:
function triggerOnChange(e) {
MailApp.sendEmail('john.doe#gmail.com', 'Testing triggerOnChange', JSON.stringify(e));
}
Then in the Script Editor menu: Resources -> Current Project Triggers -> Add a new trigger -> ['triggerOnChange', 'From spreadsheet', 'On change']
On how to change the case of the formula's result, I think #Rubén has the right idea, but it will only work if the formula contains UPPER() in the first characters, and also since you're using the formula IMPORTHTML() using UPPER() will break it and maybe some other functions like array formulas, unless you use INDEX():
=INDEX(UPPER(IMPORTHTML(url, query, index)))
Another option could be Regular expressions, but I think it's a little risky considering all the combinations.
So, anyone know a way to do exactly what the above code does, but not touch the actual formulas inside the cells, only the text that they output?
Consider to make a slight change in the OP approach: rather than capitalize all the cells content for any case, capitalize according the following conditions:
If the cell value, including the values of cells that holds constants or formulas, is not a string then do nothing .
If the cell value is a string
and the cell content is a constant, then change the case directly from the script.
and the cell content is a formula, then nest the original formula inside the built-in function UPPER.
Example:
function onEdit(e) {
var range = e.range;
var value = range.getValue();
var sheet = range.getSheet();
var sheetName = sheet.getName();
if (sheetName === 'Sheet1' &&
range.getRow() > 1 &&
range.getColumn() > 1 &&
typeof value === 'string') {
if(!range.getFormula()) {
range.setValue(value.toUpperCase());
} else {
if(range.getFormula().substring(0,6).toUpperCase() == '=UPPER') {
return;
} else {
range.setFormula('=UPPER(' + range.getFormula().substring(1) + ')');
}
}
}
}
Notes:
For simplicity the ind array was not included.
typeof e.value always returns 'string', so instead range.getValue(); is used.

If statement in a switch

I am working on a question for a course for learning javascript. I am running into trouble trying to add an if statement inside of a switch. I currently have:
var user = prompt("Are you ready for battle?!").toUpperCase();
switch(user) {
case'YES':
if(YES && NO) {
console.log("Great, let's do it.");
} else {
console.log("Bye");
}
console.log("Great! It will be a long exciting battle.");
break;
case'NO':
console.log("Come back when you are ready.");
break;
case'MAYBE':
console.log("Go away. This is only for the brave");
break;
default:
console.log("You obviously do not belong here. It was a simple yes/no question.")
}
The question is this:
Add some if/else statements to your cases that check to see whether one
condition and another condition are true, as well as whether one condition
or another condition are true. Use && and || at least one time each.
The error I am getting is this: ReferenceError: YES is not defined
What can I put in the if's condition to make this work or how do I define YES?
It would appear that you have two problems working against you here.
First is the issue pointed out in comments that you're treating YES and NO like variables, and they aren't. To avoid robbing you of the opportunity to learn by providing a corrected version of your code, I'll only give relevant examples.
var word = "test";
// If we compare against the string literally, it will have an error
// because it's looking for a variable with that name.
if (word === test) { } // ReferenceError: test is not defined
// we fix this by quoting what we're comparing against
if (word === "test") { } // Code inside the block would be executed :)
// But what about checking the value of "test" by itself?
// A string is "truthy", meaning that it passes the conditional test always.
if ("test") { } // Code would be executed always regardless of the content of var word
// Stringing multiple constants together doesn't make sense
if ("test" && "word") { } // This is equivalent...
if (true && true) { } // ... to this, which doesn't make sense
This brings us to the second problem you're trying to solve. The requirements for your problem specify checking if one condition AND another are true, as well as one condition OR another. The problem is that you only have one conditional to check: the status of the variable user.
It only makes sense to test the condition of something if you don't know what it is. Input received from a user is a perfect example. So I'd recommend that you take more inputs from the user such as name, age, gender, shoe size, or anything else. You can then check conditions as follows:
// You would need to store user input in variables username and age previously...
if (username === "vastlysuperiorman" && age < 13) { console.log("You're awfully young!"); }
// Or to only allow people within an age range...
if (age < 13 || age > 31) { console.log("You must be between 13 and 31 years old to play this game!"); }
Once you have multiple conditions to check, you can check them anywhere--inside a function, inside a case statement, inside another if. It doesn't matter. Just add an if block and test the conditions. :)

Categories

Resources