Syntax for an onChange event - javascript

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! :)

Related

Change table depending on radiobutton selection

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

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");
}

jQuery - Simple validation for two inputs

I have two inputs: the first one is X - file upload. the second one is Y- an input for an URL.
So far I have a code that checks if Y is valid then remove the attribute required for X. otherwise I want the X to be required.
$(Y).blur(function(){
if ($(this).is(':valid') == true) {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false) {
$(X).attr('required');
}
});
for some reason this code works when the input Y is valid it removes the attribute. But let's say the user regrets and wants to leave Y blank, it doesn't return the required attribute for X.
Tried to keep the explanation as simple and clear as possible. If there is a misunderstanding I'll try to edit this question and make it clearer.
The easiest way is:
$(Y).blur(function(){
if ($(this).is(':valid') == true && $(this).val() != '') {
$(X).removeAttr('required')
} else if ($(this).is(':valid') == false || $(this).val() == '') {
$(X).attr('required');
}
});
In that case when user removes the content, required attribute will be returned back (dont forget to add trim function, I didnt use it in the sample).
I would recommend to capsulate this logic into validation functions. I also dont like blur event (usability is bad), I would recommend onchange event for field validation.

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. :)

Simplify this If statement so it doesn't duplicate code - Javascript

I have an If statement that runs within a 'for' loop to create markers for a Google map. Basically if a tick box is not ticked it runs the code all displays all markers, but if a checkbox is ticked then it checks for a 2nd parameter and only runs the code for the items that match this condition.
The code I have below works fine, but it means I have to use the same code in both parts of the if statement. Apart from building it into a function if there a better way of structuring the If statement to achieve this?
if(!FriendlyChecked){
//Code here
} else if(FriendlyChecked && Friendly == "Yes"){
//Same code here
}
If FriendlyChecked is false, the first condition is satisfied and the code will be executed.
Thus, if the second condition is reached, FriendlyChecked must be true, so you don't need to check it at all, you only need to check that Friendly == "Yes".
if(!FriendlyChecked || Friendly == "Yes"){
// code here
}
if( !FriendlyChecked || (FriendlyChecked && Friendly == "Yes") ) {
// your code
}
!FriendlyChecked || (FriendlyChecked && Friendly == "Yes") will check for either FriendlyChecked is false (not checked)
OR FriendlyChecked is true an value of Friendly is Yes
This will solve your problem
if((!FriendlyChecked) ||((FriendlyChecked)&&(Friendly == "Yes")){
//Code here
}

Categories

Resources