Javascript innerHTML method returning wrong value - javascript

I'm looking for some support with this math's project I'm doing. Basically I've created four boxes, and populated one with the correct answer. When I click on the correct answer, the if statement doesn't run; it always shows as wrong.
I include a snippet, if someone can see something glaringly wrong then I'd appreciate a response.
I'm only trying it with box 1 to see if it works, and the correct answer does populate in 1 of the 4 boxes, however it always says it's the wrong answer, even when correct answer is in box1.
document.getElementById("box1").onclick = function() {
if (playing == true) {
if (this.innerHTML == correctAnswer) {
score++;
document.getElementById("scorevalue").innerHTML = score;
hide("wrong");
show("correct");
setTimeout(function() {
hide("correct");
}, 1000);
} else {
hide("correct");
show("wrong");
setTimeout(function() {
hide("wrong");
}, 1000);
}
}
}

Instead of comparing two values with ==, try === in your if-statements.
Example: if (playing === true) {

This is most likely related to your HTML, and the way you have setup your tags. For example, if box1 is a div, then if your code looks like this:
<div id="box1">
answer
</div>
Then in some explorers, specifically Chrome and FireFox, it considers linebreak as empty space.
So, if var correctAnswer = "answer";
and you compare correctAnswer with box1.innerHTML like so:
if (correctAnswer == box1.innerHTML)
Then you will always get false returned.
In order to fix the issue, change your HTML like so:
<div id="box1">answer</div>
Basically remove the linebreaks.
Everything else seems to be fine.

Related

Problem with Quiz that doesn't print result when onClick

I'm a beginner in Javascript and I have been trying to create a Quiz, but my code doesn't print result and I don't know which could be a problem.
function onlyCheck() {
var resposta = document.getElementByName("res").value;
if (resposta == perguntas.respostaCorreta[0]) {
document.getElementById("acerto").innerHTML = "Acertou";
} else {
document.getElementById("acerto").innerHTML = "Errou";
}
https://codepen.io/braian-christian/pen/GRRKdVg
Here's a fixed version: https://codepen.io/kshetline/pen/KKKPezX
What I changed was:
I took the value="x" out of the buttons and used onclick="onlyCheck(x)" (where x is 0-3) instead.
Changed your onlyCheck function like this:
function onlyCheck(resposta) {
if (resposta == perguntas.respostaCorreta) {
...
This was the biggest problem, since document.getElementByName("res").value was always going to match the first button, no matter what, since all of the buttons have the same name, and because perguntas.respostaCorreta was defined, but not perguntas.respostaCorreta[0].
Took out the <form>...</form> tags.
For one, getElementByName is plural, getElementsByName, and returns a NodeList, basically an array of elements. Also, I don't see where you're trying to print anything. What are you trying to accomplish when the button is clicked?

Find and replace HTML text with javascript

Using a WYSIWYG type web page creator that links up to various databases to pull in information from the clients servers.
One variable is for frequency and has three possible outputs, MO, YR or it is blank.
This is my HTML for one place (this can appear multiple times, just switching out the 1 with the next number)
<span style="font-size:24px;"><strong>$##1_Price</strong></span><span style="font-size:18px;" class="rateFrequency">##1_rateFrequency</span>
I am looking to use javascript to replace the MO or YR with /month and /year and doing nothing when it fills in blank.
Not much knowledge in javascript, so not sure where to begin. Was thinking somthing along the lines of this, but not sure if I am going in the right direction or where to move forward from here
<script>
window.onload=function change() {
var frequency = document.getElementsByClassName("rateFrequency");
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
}
change();
</script>
Anything to help me move forward would be great. Thanks!
Assuming I have understood your requirements correctly, the following code should do the trick, no matter how many "rateFrequency" spans are in the HTML document.
window.onload = function(e) {
function changeFreq() {
var els = document.getElementsByClassName("rateFrequency"),
len = els.length;
while (len--){
els.item(len).innerText = els.item(len).innerText.replace('MO', '/month').replace('YR', '/year');
}
}
changeFreq();
};
No if is required here. If the text contained in the span is 'MO', the first replace will replace it with '/month' and the second replace won't do anything. If the text contained in the span is 'YR', the first replace won't do anything, and the second replace will replace it with '/year'. If the text in the span is anything other than 'MO' or 'YR', neither replace will do anything, and the text in the span will remain unchanged.
I have made codepen for you to take a look at. It uses jquery, which I suggest you use because it is awesome!
Let me know if you have question:
Example
$(document).ready(function(){
$.each($('.rateFrequency'),function(){
frq = $(this).text();
if (frq=='MO'){
console.log('REPLACE MONTH');
$(this).text('/month');
}else if(frq=='YR'){
console.log('REPLACE YEAR');
$(this).text('/year');
}
})
})

How to user a condition in a String inside an IF sentence

I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}

jquery getting value from input

This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.

Show alert after all requirements have been met

I have a form where the user can 1.) check one option and be done. or 2.) check the other option and fill out a text field.
Whole thing is, after all is said and done I'd like for my alert to show, but it doesn't.
$('.know-your-role').show('fast', function() {
var $checkboxes = $('input:checkbox.checkchoice');
if($checkboxes.is(':checked')){
// show this after checked and the input has been filled.
alert('cool');
}else if($checkboxes.is(':checked') & $(".year").va() != "" ){
alert('cool');
}
});
How do I get the alert to show after all requirements (checkboxes and input) have been met?
I've made a fiddle here to show what I'm working with.
Thank you for your help in advance.
As well as the previous correct answers (missing & and misspelled val) there is a more fundamental logical issue here. You seem to have this structure:
if (conditionA) {
// behaviorA
} else if (conditionA && conditionB) {
// behaviorB
}
You will never reach behaviorB with such logic. If conditionA fails then conditionA && conditionB will certainly also fail.
Do you need to reverse the order of your if and else-if blocks?
Missing '&'
$checkboxes.is(':checked') && $(".year").val() != ""
You should use && instead of & for boolean comparisons, and also you appear to have mis-typed val as va.
I would suggest having two events, one on the 'Teacher' check box being checked and one on the year field being completed. Both events can trigger a single function that shows your alert and whatever other logic you want. So there is little duplication.
This helps to separate the events from the logic that shows/hides the year field and more easily allows you to perform different actions for the two events if that's a requirement.

Categories