JavaScript variable not global throughout AJAX refreshes? - javascript

I'm building a really simple quiz: http://fh80.student.eda.kent.ac.uk/fyp-assets/quiz/quiz.php
At the end of the quiz it should display how many you got right e.g 5/10.
One thing about it is that each question is pulled in via AJAX so every question is a different .php file. Also, for every question there is the question page and an answer page. E.g question1.php and question1a.php
I've created a variable on the page for the score:
/* Quiz Score */
var quizScore = 0;
When you load up question1.php through AJAX, there is this script:
document.getElementById("nextQuestion1a").onclick = function(){
var correctAnswer = document.getElementById("lightningbolt");
if (correctAnswer.checked){
quizScore = quizScore+1;
}else{}};
The correct answer has an ID of lightningbolt
<input type="radio" name="question1" value="lightningbolt" id="lightningbolt">Lightning Bolt<br>
So, when this input/radio button is checked it should follow the function and +1 to quizScore;
if (correctAnswer.checked){
quizScore = quizScore+1;
I think this isn't working, because the event handler for doing this is onClick of nextQuestion(ID) - this is the same button which launches the AJAX which takes you to the next page (in this case, clicking nextQuestion1a takes you to question1a.php)
So I am thinking I need to bind it different somehow. Like not on click of that button, but just on check of the radio button.
At the end of the quiz I output the score as such:
<h3>
You got
<script>document.write(quizScore);</script>
/10
</h3>
But this doesn't output any value, not even 0 as the variable was initialised.
ETA: the variable does exist on the page at all times. The variable is not declared within the refreshed content. So the variable is always there.

Related

Need to click on input twice to see result

I have written a function to fetch the number of tags of a specific id on a page but need to click twice on the input in order to get the results to display. The actual filtering works on the first click but the number of results displaying only refreshes if I click the same input a second time once the page reloads. Below is the code I am using to designate the function and then call it. Any insight would be helpful.
function elementCount(){
var x = document.querySelectorAll('.box-shodow-container').length;
var y = x - 1;
document.getElementById('resource-count').innerHTML=y;
}
<input type="checkbox" onClick="elementCount()" value="Ask the Expert" name="apf" class="checkbox-primary" />

jquery not showing live data unless refresh [duplicate]

This question already has an answer here:
refresh jquery data constantly
(1 answer)
Closed 8 years ago.
I am trying to count the amount of dropdowns that have a specific item selected in them. I have my code below, but it works like this:
select options in the drop downs, press refresh page, selected items in drop down remain there, and the script reads the amount of times each were selected.
The dropdown boxes are listed on the page with questions. there are about 100 dropdowns. every drop down has the same options.
this is a repeating code that lists all the drop down selections on the right side of the page, and shows the number of how many times each was used next to it. it works, just not dynamically. I want it to work instantly when an item is selected, without having to make selections and then refresh.
<%
mySQL="SELECT * FROM admins WHERE area="&parea&" AND type>2"
call getFromDatabase(mySQL, rstemp4, "addscheduleform5.asp")
do while Not rstemp4.EOF
pempidw=rstemp4("idadmin")
pempname1=rstemp4("firstname")
%>
<%=pempname%>=
<script type="text/javascript">
var scheduled = $("select").filter(function() {
return $(this).val() == "<%=pempidw%>";
});
document.write(scheduled.length);
</script>
<%rstemp4.movenext
loop%>
EXAMPLE:
For example, if you have 5 dropdowns. so if you select
X, A, B, X, A
in the drop downs, the code reads
X=2 A=2 B=1
Now it works, if you make your dropdown selections, and refresh the page, the drop down selections remain the same, and the code reads the amount of times each were selected.
Now if you change your first option from
X to A,
then the code still reads:
X=2 A=2 B=1
unless you refresh the page, then you see:
X=1 A=3 B=1.
For those that don't know asp, this javascript function has nothing to do with my site being asp. the "<%=pempidw%>" simply displays a number on the loaded page, referencing the select value.
see below what the loaded script would appear as.for reference on what "<%=pempidw%>" means only
<option value="2">2</option>
<script type="text/javascript">
var scheduled = $("select").filter(function() {
return $(this).val() == "2";
});
document.write(scheduled.length);
</script>
Given document.write really isn't a good way of doing this, I'm going to (for the sake of the example) place a <span id="result"></span> on thepage we can [re]reference with the output.
Having said that, the test code should be wrapped in a function so we can re-use it. Currently it's only executing on the initial visit to the page. To correct that, we're also going to execute our new function on a change to any of the dropdowns.
function getSelectedValues(){
var matches = $('select').filter(function(){
return $(this).val() == '<%=pempidw%>';
}).length;
// here's where we just update that new <span>
$('span#result').text(matches);
}
// call it on initial page visit
getSelectedValues();
// and here we bind to the change event for the selects
// and re-call our above function.
$('select').on('change', getSelectedValues);

Prematurely exiting a Loop and Merge block in Qualtrics

I'm currently working on a Qualtrics survey in which respondents have to solve a long list of anagrams, and then answer some demographic questions.
To make the anagram part easier, I've used a Loop and Merge block: the first field is the anagram to be solved, the second field is the solution of the anagram, and the survey can therefore check the answer of the respondent against the solution for each anagram.
As it is, the survey is working perfectly: however, I'd like to allow respondents to prematurely exit the loop by typing "EXIT" in the response field, and to redirect them to the next question block (the demographic questions).
This is typically something that is achieved using "Skip" logic: however, skipping to the end of the block does not do the trick (the loop restarts). I managed to redirect them to the end of the survey, but not to the demographic question block.
Is there a way to use javascript to jump to the demographic block or exit the loop and merge block prematurely? Am I missing a Qualtrics option that would do the trick?
If this is still relevant to you: I needed the same functionality and this is how I solved it: First, I define a helper variable, call it EndLoop, which I initialize to 0. Then I set up a function to change the value of EndLoop to 1 after people hit a button, additionally I add a display logic to the question in the loop showing them only if EndLoop is still 0 and hiding the questions as soon as EndLoop is 1.
This is a step-by-step instruction and the javascript and html code.
The bold stuff is what you need to do, the bulletpoints a more detailed instruction how to do it.
1. Before your loop-and-merge define an embedded data field called EndLoop and initialize it as 0.
Go to the Survey Flow Panel
Add a new element > select embedded data field
Name the field 'EndLoop'
Set its value t0 the number 0 by click on the link "set value now"
Make sure you move it before the merge-and-loop block
2. For each item in the loop set a display logic to show them conditional on 'EndLoop' = 0
Go to the options menu of each question in the loop
Select "add display logic"
Select "Embedded Data" from the first dropdown menu
A new type field opens > as name type EndLoop + select "is equal to" + type 0 as value
3. Insert a customized button into the page where people should be able to opt-out. The button runs a user-defined function called setEndLoop() onclick.
Click on the question where the button should appear
On the top-right of the question text select "html view"
The code I used is:
<input id="css-class-mybutton" onclick="setEndLoop()" value=" done " type="button">
If you want to change the button text, change the " done " in value = " done "
4. Define the function setEndLoop() using custom javascript to change the value of EndLoop to 1 and emulate a next button click
Go to the options menu of each question in the loop
Select "add JavaScript"
The code I used is:
/* Get the EndLoop variable */
var EndLoop = "${e://Field/EndLoop}";
Qualtrics.SurveyEngine.addOnload(function(){
/* hide previous and next button */
$('NextButton') && $('NextButton').hide();
$('PreviousButton') && $('PreviousButton').hide();
/* Function: on click on user-defined button -> change the field EndLoop */
var that = this;
setEndLoop = function(){
Qualtrics.SurveyEngine.setEmbeddedData('EndLoop', 1);
that.clickNextButton();
};
});
The button will not have the default style, thus, define a custom css to style your button to look like the buttons of your theme. The class name for the button I used here is id="css-class-mybutton", use .css-class-mybutton{ ... } in the css.
Hope that helps.
I know this is a bit late, but I had a similar issue and wanted to post an alternative solution. I used the loop and merge function, but I didn't want to have participants click on a button to exit the loop, instead I wanted to use a multiple choice question to exit the loop. This question was, "would you like to ask more questions?", with responses yes and no. If the participant selected "Yes" they would keep going through the loop and if they selected "No" they would exit the loop and go on to the next block of questions.
My first two steps are the same as those above.
1.Set up an Embedded data field named EndLoop and set the value to 1.
- in the survey flow panel select add an element. Then type in the name EndLoop.
- Then select set value now and set the value to 1.
- make sure that this is before your loop and merge block in the survey flow.
For each question in the loop and merge block use display logic to ensure that they only display when the embedded data element EndLoop is 1.
Now for the question "would you like to ask more questions?" add the following code in the add javascript area.
the javascript area can be found by clicking the advanced options button under the question number on the lefthand side of the screen. Select 'Add javascript...'
There will be some code already present...it should look like this:
Qualtrics.SurveyEngine.addOnload(function()
{
/Place Your Javascript Below This Line/
});
Basically I used event tracking to update the embedded data field EndLoop to the numerical value associated with the answer choice when the answer choice was selected. In this case the answer "Yes" had a value of 1 because it was the first option and "No" had a value of 2 because it was the second option. When "No" was selected, the embedded data field EndLoop was set to a value of 2. This then meant that none of the questions would display since they have display logic to ensure they only display when the EndLoop field is 1.
My entire code looks like this:
Qualtrics.SurveyEngine.addOnload(function ()
{
this.questionclick = function(event,element)
{
console.log(event, element);
if (element.type == 'radio')
{
var choiceNum = element.id;
if (choiceNum == 2)
{
Qualtrics.SurveyEngine.setEmbeddedData("EndLoop", choiceNum);
}
}
}
});
I used the second solution. Here's a minor correction for the script:
I wrote element.id.split('~')[2] instead of element.id, and it worked!
Qualtrics.SurveyEngine.addOnload(function ()
{
this.questionclick = function(event,element)
{
console.log(event,element);
if (element.type == 'radio')
{
var choiceNum = element.id.split('~')[2];
if (choiceNum == 2)
{
Qualtrics.SurveyEngine.setEmbeddedData("EndLoop", choiceNum);
}
}
}
});

JS Replacing form inputs with user input

I'm a novice with javascript, and am struggling with my final project for a class. We're essentially making an online quiz. It's a math quiz, and I've set up forms with text input fields for the answer, and those forms are within div containers. I'm trying to create a function that, upon clicking a submit button, will pull the value of the user's input, and use that value to replace the form as the inner html of the div. This way the answer will be committed and cannot be changed after the user submits their answer. One key step of this is that the digits of the answer are entered individually - a field for the tens column, a field for the ones. I'm trying to pull those separately, concatenate them, and then compare them with the calculated actual answer. The actual answer will replace the submit button, color coded to reflect whether the user was correct or not. Here's what I have:
var firstNumber = Math.floor((Math.random()*50)+1);
var secondNumber = Math.floor((Math.random()*50)+1);
var generate = function(){
document.getElementById("addends1").innerHTML=firstNumber;
document.getElementById("addends2").innerHTML=secondNumber;
};
var evaluate = function(){
var result = firstNumber+secondNumber;
document.getElementById("button").innerHTML=result;
var tens = document.getElementById("result10s").value;
var ones = document.getElementById("result1s").value;
var entry = tens + ones;
document.getElementById("resultContainer").innerHTML=entry;
var cO = document.getElementById("cO").value;
document.getElementById("carryOverContainer").innerHTML=cO;
var answer = parseFloat(entry);
if (answer===result) {
document.getElementbyID("resultContainer").style.color="#b2f078";
} else {
document.getElementbyID("resultContainer").style.color="#e87c73";
}
};
document.getElementById("button").onclick=evaluate();
(the first function is called in the html tag, onload for the button image)
Thanks!
Edit: My problem is just that my code isn't doing anything at all. I don't know if that has to do with how I'm calling the "evaluate" function, or the function itself. I want to replace all form fields with their entered values, and then also replace the button with the correct answer to the addition problem. Here's my html:
<body>
<div id="carryOverContainer">
<form>
<input type="text" name="carryOver" id="cO"/>
</form>
</div>
<div id="addends1" class="addends"> </div>
<div id="addends2" class="addends"> </div>
<div id="resultContainer">
<form>
<input type="text" id="result10s" class="result">
<input type="text" id="result1s" class="result">
</form>
</div>
<div id="button" onclick=evaluate();>
<img src="next.png" alt="next" onload="generate();"/>
</div>
</body>
I'm suspecting the problem may lie in how I'm trying to pull and store the values from the form fields?
As there are potentially many issues, I'll help you in steps rather than try to give you the whole solution. (It's the weekend now, so I can respond more frequently.)
The first issue is in the way you're defining and using functions. Your syntax, i.e.
var evaluate = function() {
// ...
}
defines an anonymous function assigned to the variable generate. For comparison, here's how regular functions are defined:
function evaluate() {
// ...
}
Your syntax can work if called properly, but you're calling it like a regular function:
document.getElementById("button").onclick=evaluate();
What's happening is, whereas for a regular function, the function evaluate() would get assigned to the onclick event, for an anonymous function, evaluate and () are interpreted as call the anonymous function in this variable. Therefore, evaluate() is getting called right away, instead of onclick! Here's a JSFiddle that shows how your form fields are immediately replaced.
Once you've fixed this issue, update your question and comment on my answer to grab my attention, and we'll take it from there.
By the way, if you're using Chrome, hit CtrlShiftI and go to the Console tab to see if your Javascript is throwing any issues. Firefox has a similar feature—look for developer tools in the menu.

JavaScript variable passed to PHP

I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];

Categories