Calling upon a global variable - javascript

This is intended to be a one question quiz. When you choose your answer and hit "submit" it should output your answer and your score out of 1.
The problem is it isn't reading "var response" correctly - it comes out undefined.
I was hoping a second set of eyes can help me address the problem
All help is appreciated :)
<p id="question">
<button type="button" class="start" onclick="test();">Start</button>
</p>
<p id="here"></p>
<script>
function test() {
document.getElementById("question").innerHTML =
"<p>What color is the sky? <select id='list' onchange='score();'><option value='Not Sure' selected>Not Sure</option><option value='Blue'>Blue</option><option value='Red'>Red</option></select></p><button type='button' onclick='submit();'>submit</button>";
}
var total = 0;
var response = document.getElementById('list').value;
function score() {
var response = document.getElementById('list').value;
if (response === "Blue") {
total++;
}
}
function submit() {
document.getElementById("here").innerHTML =
"Your Answer:" + response + "<br />" + total + "/1";
}
</script>

You currently have two response variables, the first one being global and assigned to a value from a field that doesn't exist yet, and the second being local within the score() function.
You need to declare the variable outside the functions, but set its value inside score():
function test() {
document.getElementById("question").innerHTML =
"<p>What color is the sky? <select id='list' onchange='score();'><option value='Not Sure' selected>Not Sure</option><option value='Blue'>Blue</option><option value='Red'>Red</option></select></p><button type='button' onclick='submit();'>submit</button>";
}
var total = 0;
var response = "Not sure";
function score() {
// 'var' removed from following line:
response = document.getElementById('list').value;
if (response === "Blue") {
total++;
}
}
function submit() {
document.getElementById("here").innerHTML =
"Your Answer:" + response + "<br />" + total + "/1";
}
<p id="question">
<button type="button" class="start" onclick="test();">Start</button>
</p>
<p id="here"></p>
(Also, not what you're asking, but it doesn't make sense to call score() from the select element's onchange, because if the user changes their mind back and forth from Blue to Red several times then the total variable gets incremented several times and they can get a score like 3/1. It would be better to do all the calculations in response to the submit button click.)

You can remove the "var" inside the below method which is redefining the global variable inside the function scope.
function score() {
response = document.getElementById('list').value;
if (response === "Blue") {
total++;
}
}

The problem seems to be with this line
var response = document.getElementById('list').value;
When this line is parsed there is not element with id list present in dom. Hence you are seeing undefined.
You can try by assigning this variable inside the test function
function test() {
document.getElementById("question").innerHTML =
"<p>What color is the sky? <select id='list' onchange='score();'><option value='Not Sure' selected>Not Sure</option><option value='Blue'>Blue</option><option value='Red'>Red</option></select></p><button type='button' onclick='submit();'>submit</button>";
response = document.getElementById('list').value;
}
DEMO

Related

Outdated value issue in JavaScript form

Here's the HTML:
<input type="text" placeholder="Answer..." id="ansbox1">
<input type="submit" onclick="submit1();" id="sp1">
Here's my JS:
var txt1 = document.getElementById("ansbox1").value;
function submit1() {
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {
alert("Nope, its wrong!");
}
}
When I put (even the decoded matching string) in the input box, it still always shows "Nope, its wrong!".
Any error?
I referred to this, yet I still get the same issue...
JS - Check if the input field equals the solution
Since txt1 is outside the function call, it has stale data. Put it inside the function call, so it can be updated everytime.
function submit1() {
var txt1 = document.getElementById("ansbox1").value;
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {alert("Nope, its wrong!");}
}
Your txt1 variable is outside the function, which could have a stale/previous value.
This variable should be put inside the function so that it's always updated:
function submit1() {
var txt1 = document.getElementById("ansbox1").value;
if (txt1.split(" ").join("") === atob("[base64string]").split(" ").join("")) {
alert("Yaay!");
}
else {
alert("Nope, its wrong!");
}
}

Storing / passing a variable to another function

I have a simple problem storing and passing a variable from one function to another. My script should work like this:
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="write()">
<p id="ag"></p>
If somebody enters a value in the input field "ip1" and presses the "check_button", the value should be stored in a variable. This variable should be written in the innerHTML of "ag" when the "write_button" is clicked.
This is my JS. I am aware that this cannot work, I just don't know how to do it properly. I found similar problems but the solution always seems to complex for a beginner like myself to understand. A very easy solution would be very much appreciated!
function check_text() {
var ui = document.getElementById('ip1').value;
}
function write() {
document.getElementById('ag').innerHTML = ui;
}
You should declare variable outside the function:
it must work
var ui = 0;
function check_text() {
ui = document.getElementById('ip1').value;
}
function writeL() {
document.getElementById('ag').innerHTML = ui;
}
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="writeL()">
<p id="ag"></p>
There are of course more than one way to process your value. The Snippet below uses the HTMLFormControlsCollection. Details are commented in the Snippet. BTW, I had to get rid of one of the buttons, it would probably hinder your understanding rather than aid it. It's better to visualize what's happening by watching the console.
SNIPPET
/***NOTE: Any comment having a pencil icon: ✎
|| means that the expression/statement is there...
||...to show an alternate way. Although they...
||...aren't used in the functions, they can be...
||...used instead of it's counterpart.
*/
function processData() {
// Reference the <form> by id or...
var form1 = document.getElementById('form1');
// ✎
/*1*/
console.log('1. This is ' + form1.id + '\n');
/*...or by HTMLFormControlsCollection...
||...reference <form> as the first <form>...
||...the .forms is an array-like object...
||...the [0] is the index indicating which...
||...<form> it's referring to. This is easily...
||...determined since there's only one <form>...
||...on the page.
*/
var formA = document.forms[0];
/*2*/
console.log('2. This is ' + formA.id + '\n');
// We'll continue using the HTMLFormControlsCollection
/* This is using previously declared formA to...
||...reference it's .elements property. The...
||...elements property is like the .forms...
||...except that it refers to a <form>'s...
||...field form elements like <input> and ...
||...<output>
*/
var formUI = formA.elements;
/*3*/
console.log('3. This is an ' + formUI + '\n');
// We can get the number of form control elements
var qty = formUI.length;
// ✎
/*4*/
console.log('4. form1 has ' + qty + ' form control elements\n');
/* Get the value of text1 by using the object formUI...
||...the name of <input>, and the .value property.
*/
var TXT1 = formUI.text1.value;
/*5*/
console.log('5. The value of text1 is ' + TXT1 + '\n');
/* We can get the same result by referencing <input>...
|| ...by it's index position in the formUI object...
|| This expression is getting the value of the first...
||...form field element of the <form> or formUI object
*/
var TXTA = formUI[0].value;
// ✎
/*6*/
console.log('6. The value of Text1 is still ' + TXTA + '\n');
/* Return the value of TXT1
|| This function returns a value, so it can be...
||...assigned to a var as a value and it can be...
||...passed through another function like a...
||...parameter.
*/
return TXT1;
}
/* This will pass a value...
||...reference the <output>...
||...and set <output> value to...
||...given value
*/
function displayData(value) {
var output1 = document.getElementById('output1');
output1.value = value;
}
/* When button1 is clicked...
||...store the return of processData() in a var...
||...then pass that var to displayData() function
*/
document.getElementById('button1').onclick = function(event) {
var VAL = processData();
displayData(VAL);
}
input {
font: inherit
}
<form id='form1' name='form1'>
<input type="text" id="text1" name='text1'>
<input type="button" value="display" id='button1'>
<br/>
<output id="output1" name='output1'></output>
</form>
You can do it easily with jQuery like this:
var enteredValue = "";
$("#check_button").on("click", function() {
enteredValue = $("#ip1").val();
});
$("#write_button").on("click", function() {
$('#store_value').html(enteredValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ip1" />
<input type="button" id="check_button" value="checking" />
<input type="button" id="write_button" value="write" />
<p id="store_value"></p>

onClick Button Only Works Once

I have a button that checks input text to see if it is the right password. The problem is that the button only works once and when you click multiple times it doesn't run the function over and over again.
My Code:
<html>
<head>
<title>Password</title>
<script>
function passcheck() {
var attempts = 5;
var q = document.getElementById('txt').value;
if (q == "12345") {
document.getElementById("result").innerHTML = "You're In!";
} else {
attempts--;
document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
}
}
</script>
</head>
<body>
<font face="Verdana" size="5"><b>Enter Your Password:</b></font>
<br/><br/>
<input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
<button type="button" onclick="passcheck()">Submit!</button>
<p id="result"></p>
</body>
</html>
It is being called multiple times, but you aren't seeing a change because attempts is defined inside of the function. That means that every time you run that functions, attempts is being reset to 5. To fix that, move the attempts declaration outside of the function.
var attempts = 5; // Moved to here so we don't reset the value
function passcheck() {
var q = document.getElementById('txt').value;
if (q == "12345") {
document.getElementById("result").innerHTML = "You're In!";
} else {
attempts--;
document.getElementById("result").innerHTML = "Wrong password, You Have " + attempts + " Tries Left!";
}
}
<font face="Verdana" size="5"><b>Enter Your Password:</b></font>
<br/>
<br/>
<input id="txt" type="text" onclick="this.select()" style="text-align:center;" width="25">
<button type="button" onclick="passcheck()">Submit!</button>
<p id="result"></p>
You are initializing the value of "attempts" and decrementing it every time you call the function. Hence it seems like the function is being called only once.
Move the deceleration of the variable outside the function. Something like
var attempts = 5;
function passcheck() {
//code here ...
}
Another slightly better way would be to make use of localStorage or sessionStorage or even using cookies.
Thanks,
Paras

Getting the value of prompt box into another function

Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
If you want to directly pass value to dis() function then change your script to
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis() function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null but the case element will still be visible.

innerHTML in function (Global variables?)

I'm struggling to get this working. The dispatch() function seems to be getting triggered (tested with the alert), but the innerHTML lines don't seem to work.
Also, i doesn't seem to increase despite the i++ in the onSubmit.
Here is the function in question:
function dispatch(passengers,i,timesArray)
{
alert('value of i is '+i);
timesArray[i]=getTime();
var avTime=getAverageTime(timesArrary);
var throughput=passengers*3600000/avTime;
if(i==0)
{
document.getElementById('output').innerHTML = 'Calculating...';
}
else
{
document.getElementById('output').innerHTML = throughput;
}
//and possibly a list (w/e)
}
And here is the form:
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);i++;">
<input type="text" name="numApples" id="numPassengers" />
<br/>
<input type="submit" name="Submit" value="Press on Dispatch!"/>
</form>
Could this be a question of not being able to change global variables from inside the function?
Or, is there something wrong with the avTime or throughput lines which is making the function cease?
In this line:
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);i++;">
i is a global variable, but in dispatch() i is an argument which is not in global scope. Inside dispatch() it is in local scope of that function, and can't be increased in global scope. Hence I think your onSubmit()should be:
onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);num++;">
Why is the variable being increased outside the function? Shouldn't it be inside the function and increased there?
Also, if num is global, you don't need to pass it as a parameter.
// global
var num = 0;
function dispatch(passengers, timesArray)
{
alert('value of num is ' + num);
timesArray[num]=getTime();
var avTime = getAverageTime(timesArrary);
var throughput = passengers * 3600000 / avTime;
if(num == 0)
{
document.getElementById('output').innerHTML = 'Calculating...';
}
else
{
document.getElementById('output').innerHTML = throughput;
}
//and possibly a list (w/e)
// increasing num here!
num++;
}
Then your form could drop the increase in the variable, and the num from the call.
<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, times)">
Cheers, Apoc.

Categories