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?
Related
It's my first app, I have been in tutorial hell for one year and decided to start my own little app.
So in this part Im using an addEventListener(),which appends and create text. The text is a variable created by the sum of the results of other functions (I don't know if this is relevant), but the thing is once I submit a button and creates the HTML element, if I keep submitting the elements will pile up. So I tried removeChild() but it didn't work because the variable was already created with its value, or...brought an error that can't removedChild() of undefined (since I tried to clear the values before appending), also tried to reseting the variable by adding a .innerHTML=""; but I don't know where to locate it. I also checked the replaceChild() but it didn't make sense, since everytime you click should be a new first event created. I tried the empty().append() but seems it's for jquery.
Seems that I need to learn a lot about scopes.
let frase;
function armarPersonaje() {
if(!reversarNombre() || !descMes || !descDia){
return false
} else {
frase = nombreReves + descMes + descDia;
return true
}
}
let div;
let h3Element;
function mostrarPersonaje(){
let div = document.getElementById('container')
let h3Element = document.createElement("h3")
h3Element.className = "addedH3"
if(frase.length > 0){
h3Element.appendChild(document.createTextNode(frase));
div.appendChild(h3Element)
}
}
enter image description here
Here's the complete code
https://jsfiddle.net/santiso/mzv3ct5e/
The problem here that in your last function mostrarPersonaje() you are always creating the element h3Element before the if , and even if you empty the parent node which is the div it will create a new element whit class addedH3 the very next click !
How to fix it ? first do not create until you enter the condition , then delete it when ever you click again even before the condition
here is the fiddle
and this is what i added
let oldH3Element = document.querySelector('h3.addedH3')
if(oldH3Element) oldH3Element.parentNode.removeChild(oldH3Element)
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.
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.
i plan to show some images on the page and when the user press up button some related new images will be shown. I have been achieving that by changing the "src" attribute already existing image html tag.
i have json data like [["a","b"],["c","d"]] which gives the name of images like a.jpg, b.jpeg etc.
Here is the problem i can not pass the array value to jquery click object. my javascript functions as below:
var a; // a global variable holding the json array [["a","b"],["c","d"]]
function rileri(){ //img next
var ix=parseInt($("#up").attr('rel'));
ix=(ix+1)%a.length;
for(var i=0;i<2;i+=1){
$("#k"+i).attr("src","img/m/t/"+a[ix][i]+".jpg");
$("#k"+i).click(function() { rgetir(a[ix][i]);}); //problem is here!!
}
$("#up").attr('rel',ix); // i keep index data of appearing img on "rel"
}
function rgetir(n){ //img down ajax
$("#brc").load("data/rgetir.php", {'name':n});
}
I wonder how can i bind click event and if there is any better solutions ?
html is like that (no "src" at start, is it ok ?):
<img id="k0"/><img id="k1"/>
<input id="up" rel="0" type="button" onclick="rileri()" value="Next">
Yeap the main problem is passing the multidimensional array value to a function :(
The problem has nothing to do with "multidimensional arrays." It is that you are using i inside the assigned click value, and i changes with every iteration of the loop. Each assigned click value holds a reference to i, so when rileri is finished each points to the same value. You need to break the reference, usually done by passing i to a function and binding the click in there.
There are many flavors of using a function to break a reference, but since you're using jQuery and iterating an array, we'll use $.each:
(what follows is untested but should serve as an example)
function rileri(){
var ix=parseInt($("#up").attr('rel'),10);
ix=(ix+1)%a.length;
$.each(a[ix], function (i) {
var img_name = this;
$("#k"+i)
.attr("src","img/m/t/"+img_name+".jpg")
.click(function () {
rgetir(img_name);
});
if (i >= 2)
{
return false;
}
});
$("#up").attr('rel',ix);
}
Here is a simple fiddle that shows your problem
http://jsfiddle.net/MHJx6/
The problem is your ix and i variables are closures, so at the time the event runs they have the wrong values as you can see in this example.
I tried to write some code that will do what I think you are trying to do below. It would be easier if I knew what you were trying to do (use case). Maybe this is what you want?
var a; // a global variable holding the json array [["a","b"],["c","d"]]
function rileri(){ //img next
$("#k0").click(function() { handleClick(0); });
$("#k1").click(function() { handleClick(1); });
}
function handleClick(index) {
var ix=parseInt($("#up").attr('rel'));
ix=(ix+1)%a.length;
$("#k"+index).attr("src","img/m/t/"+a[ix][index]+".jpg");
$("#up").attr('rel',ix);
}
So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!