Toggle on Yes/No buttons to continue on in survey - javascript

I want to know how to make sure either the Yes or No button is toggled in my survey in order to continue (so if either Yes or No has been clicked, the nextQuestion function can continue. If Yes or No has not been clicked, I will give an alert to the user to please make a selection). I currently have the progress bar and question updating in the same function. I figured it would make sense to add this bit to it but I am getting confused.
var index_question = 0;
var question_number = 2;
var progress_question = 1;
var percentage = 0;
function nextQuestion(){
if (index_question < 4) && ($(".btn-success").button('toggle')) {
<!-- Question # and Question Text -->
document.getElementById("questionArea").innerHTML = questionSet[index_question];
index_question ++;
document.getElementById("questionNum").innerHTML = [question_number];
question_number ++;
<!-- Progress Bar -->
percentage = ((([progress_question])*(100))/(5));
progress_question++;
$(".progress-bar").width([percentage] + "%");
}
<!-- Survey Completed -->
else {
$(".progress-bar").width("100%");
alert("Thank you for completing the survey!")
}
}
<td><button class="btn btn-success" type="button" onclick="questionDecision">Yes</button></td>
<td><button class="btn btn-danger" type="button" onclick="questionDecision">No</button></td>
function questionDecision() {
$(".btn btn-success").button('toggle');
$(".btn btn-danger").button('toggle');
}

One option is to have a variable in the Javascript like var answered_question = False;, which is set to True in your questionDecision function after they have made a choice. Before advancing the user to the next question or updating the progress bar, always check if(clicked_yes_or_no==True){ }.

Related

Find and Click button with JS

I'm trying to use a chrome extension (shortkeys) to create shortcut keys that can press buttons within our warehouse management system (so they can be matched to barcodes).
One of the buttons has no ID, and once it has been clicked the button innertext changes. Ideally I'd like the shortcut to work on either version of the button
It is either
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
or
<a class="btn btn-success" href="/Order/OrderDocumentP/15467" target="_blank">Print Label</a>
I then have another button to be assigned to a different shortcut key
<a class="btn btn-success" href="/Picking/DespatchOrder?OrderId=13413">Despatch</a>
But I'm sure once I've figured out the first one the next will be easier :)
Any help greatly appreciated, I've been through a number of other questions that are similar but not quite what I'm after and my JS knowledge is pretty rubbish
Learn CSS a bit and use https://developer.mozilla.org/ru/docs/Web/API/Document/querySelector
Your extensions probaply supports that
// cuz I don't like to type long "document.querySelector"
q = sel => document.querySelector(sel)
qq = sel => document.querySelectorAll(sel)
function clickOnly(sel) {
let list = qq(sel);
if (list.length == 1) list[0].click();
else alert('element "'+sel+'" is not unique!');
}
// handles *any* keypress
onkeypress = function (event) {
if (event.target.tagName == "INPUT") return; // noop on input focused
if (event.target.tagName == "TEXTAREA") return; // noop on input focused
console.log(event.code); // to see what the key is
let rawCode = event.code; // keyboard key, `KeyM` for M, `Digit7` for 7, `Slash` for /
let code = rawCode; // make CtrlAltShiftKeyM
if (event.shiftKey) code = 'Shift' + code;
if (event.altKey) code = 'Alt' + code;
if (event.ctrlKey) code = 'Ctrl' + code;
if (!kds[event.code]) return;
event.preventDefault(); // prevent CtrlKeyM browser handler for bookmarks or whatever
kds[event.code](event);
}
kds = {}
// it's a function so starts with `() => `
kds.KeyM = () => alert('it works!')
// a is for <a>, [href^=] is for href starts with
kds.ShiftKeyM = () => clickOnly('a[href^="/Order/OrderDocumentP/]')
// , is for one of multiple selectors
kds.CtrlKeyM = () => clickOnly('input[value="Create Shipment"], a[href^="/Order/OrderDocumentP/]')
This is a simple script on getting a button by class name and clicking it. I think this is what you are looking for, if not let me know I will rewrite it.
EDIT: I added a loop that will click all buttons or links found with the class name btn-success
I've inserted a second function so people looking for a solution by classname can also still find the first one. AutoClickBtnByValue() will click the button with inner text "click me now".
function AutoClickBtn() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
button[i].click();
console.log('Success! Clicked button' + i);
}
}
setInterval(AutoClickBtn, 2000);
/* Click button by innerHTML text */
function AutoClickBtnByValue() {
var button = document.getElementsByClassName("btn-success");
for (var i = 0; i < button.length; i++) {
if (button[i].innerHTML.indexOf('click me now') > -1) {
button[i].click();
console.log('Success! Clicked button' + i + ' with value: "click me now" ');
}
}
}
setInterval(AutoClickBtnByValue, 2000);
<input type="submit" value="Create Shipment" class="btn btn-success pull-right">
<a class="btn btn-success" href="#" target="_blank">Print Label</a>
<a class="btn btn-success" href="#">Despatch</a>
<button class="btn-success">click me now</button>

How to validate an user answer button click javascript

Currently I'm trying to create a quiz, right now it displays the first question with 4 answer choices after the start button I am stuck on how to retrieve the answer. The user clicks, check to see if its correct and loop to the next question. I just want to give the user one chance per question and move on regardless if it's correct or not. If their answer is wrong I will remove seconds from the timer. I have the questions, answer choices, and correct answers in arrays.
<div class="card-body">
<p id="header">
You have 75 seconds to complete this asessment.
Every incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
<script src="./script.js"></script>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"],
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime --;
timerEl.textContent = totalTime;
if(totalTime === 0){
clearInterval(timerInterval);
endQuiz();
return;
}
}, 1000);
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
console.log(i);
return;
}
}
Hi I will try to provide an easy solution to your question without using any kind of difficult javascript syntax so here goes..
First in your html file update the option button and add a class property called clickOption(you can change the class name if you want, but be sure to change in other places in script.js as well). The code is shown below.
<button id="option0" class="clickOption" data-index="0"></button><br>
<button id="option1" class="clickOption" data-index="1"></button><br>
<button id="option2" class="clickOption" data-index="2"></button><br>
<button id="option3" class="clickOption" data-index="3"></button><br>
Now in your script.js file add the line of code shown below. I have added inline comments for better understanding
// get all elements with class clickoption i.e all option buttons
var elements = document.getElementsByClassName("clickOption");
//use the below array to track the selected answers
var selectedAnswers = [];
var clickOption = function() {
/** Here I have reached the end of the test and,
I am logging the array of user-selected options.
This array can be compared with correctAnswers array
to determine whether the answer is correct or not **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
/**Get the option value that was clicked.
Here I am using parseInt because,
the data-index attribute value will be in string format,
and the correctAnswers array is in Number format so it is better,
to keep the selectedAnswers array in Number format as it will faciliate
easier data comparison**/
var selectedOption = parseInt(this.getAttribute('data-index'));
// add the selected option to the selectedAnwsers Array
selectedAnswers.push(selectedOption);
/** here I am assuming that you are using the questionNum variable
to track the current question Number **/
questionNum += 1;
/** here I am again checking if I have reached the end of test and
thus log the answers
Instead of logging the answer you can create a function
that compares the result and display it on screen **/
if(questionNum >= questions.length) {
console.log(selectedAnswers);
return;
}
// update the next question text
questionEl.textContent = questions[questionNum];
// update next options
displayQuestion(questionNum);
}
//loop through all the elements with class clickOption
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', clickOption);
}
start.addEventListener("click", function() {
timer();
/** I have updated the displayQuestion call implementation
so that the function is called with a parameter
(here the parameter it is zero) **/
displayQuestion(questionNum);
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
/**Finally I have updated the display question method
so that it updates the option buttons based on the index parameter **/
function displayQuestion(index){
questionEl.textContent = questions[index];
option0.textContent = answers[index][0];
option1.textContent = answers[index][1];
option2.textContent = answers[index][2];
option3.textContent = answers[index][3];
}
Hope this solution helps you. Happy Coding!

javascript toggle needs to stay

hi guys i need some help with javascript,
i have a toggle function for my text, waht you can see on www.jasperscheper.nl
but i want to make the text stay when you double click on over mij and home.
this is my code:
var bannerText1 = document.getElementById('bannertext1');
var bannerText2 = document.getElementById('bannertext2');
var displayedBannerText = 1;
function toggleBannerText() {
if(displayedBannerText == 1) {
// Switch to bannertext 2
bannerText1.className += ' hidebannertext';
displayedBannerText = 2;
bannertext2.className = 'welkom';
} else {
bannertext2.className += ' hidebannertext';
displayedBannerText = 1;
bannerText1.className = 'welkom';
}
}
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText()"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText()" href="#"><h3>Over mij</h3></button>
</li>
thanks in advance,
Jasper Scheper.
Problem: You are calling the function toggleBannerText() every time there is a click on any of the buttons, There is no where the button's click events are distinguished, So every click assumes you need to show other text than the one shown.
Solution: Change your HTML to pass a parameter into the function saying which section it wants to show. Eg: toggleBannerText('Home')
<li class="knop" >
<button class="button" href="#"onclick="toggleBannerText('Home')"> <h3>Home</h3></button>
</li>
<li class="knop">
<button class="button" onclick="toggleBannerText('Over')" href="#"><h3>Over mij</h3>
</button> <!-- There was a typo you had a </a> here I changed it -->
</li>
Now change your function to accept the parameter and show that particular Text .
function toggleBannerText(section) {
if(section === "Over") {
// Switch to bannertext 2
bannerText1.className = 'hidebannertext'; // I have removed the +
bannertext2.className = 'welkom';
}
else if (section === "Home"){
bannertext2.className = 'hidebannertext'; // + has been removed
bannerText1.className = 'welkom';
}
else{
// none of the two buttons were clicked.
}
}
I have tested this code against your site and its working fine

Set HTML div value using JavaScript

I have an HTML page with 2 divs (among other things) - "person" and "person-success", in which "person" is visible and "person-success" hidden. When a button in "person" is clicked, the visible div hides and the previously-hidden div "person-success" shows. The code is given below:
<div id="person">
<br><br>
<div id="counterNum" class="counter-color" l10nID="M_AC_UT_TXT_20"></div>
<div role="form">
...
<button type="submit" id="addPerson" class="btn btn-success" l10nID="M_LG_BTN_1"></button>
</div>
</div>
<div id="person-success" class="hide">
...
<p>
<span l10nID='M_AC_UT_TXT_19'></span>
You can add <span id="limit"></span> more people. <a href='<?php echo $root; ?>edituseraccount.php?action=addPerson'>Add another person?</a>
</p>
</div>
The JavaScript:
$('#addPerson').click(function() {
var counter = 0;
var limit = 10;
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
Now, when the button is pressed, while "person-success" will show, clicking on "Add another person?" should show "person" and hide "person-success" again. Only this time, the div "counterNum" should be updated with the value of "counter" from the JavaScript. With my code, clicking the link reopens the "person" div and hides the other, but counterNum is not updated, or even shown. Does anyone know how I could do that?
I hope I could explain my problem. Would be grateful for any help!!
Var counter Make it as global. Because each time when you click on the addPerson button when counter resets to zero.
var counter = 0;
var limit = 10;
$('#addPerson').click(function() {
var args = {
...
$.post("addperson.php",args,function(data){
var response = JSON.parse(data);
if(response.status == 0){
counter += 1;
if (counter < limit){
$('#counterNum').text(counter);
$('#person').hide();
$('#limit').text(limit-counter);
$('#person-success').show();
}
}
console.log(data);
});
});
The variable you declare is local scope.
Declare variable globally outside the click event called.
On each click it resets counter to 0.
Hope it helps !!!

How do I call the next and the previous value in an array with a button?

I want the "displayround" div to show a certain value in my array. When the page loads the first value in the array (1/38) is being displayed. When I press the "next" button I want it to show the next value in the array (2/38) and so on. And when I press "previous" button I want it to display the value that comes before the displayed value.
HTML:
<div id="buttonholder">
<button id="previous">< Previous round</button>
<button id="next">Next round ></button>
<button id="current">> Current round <</button>
<div style="font-size: 0;">
<form id="inputfield">
<input type="inputfield" value="Search for round here..."></input>
<button id="submit">Go</button>
</form>
</div>
<div id="displayround">
</div>
</div>
My Jquery/javascript:
$(document).ready(function() {
var round = new Array();
round[0]="1/38";
round[1]="2/38";
round[2]="3/38";
round[3]="4/38";
round[4]="5/38";
round[5]="6/38";
round[6]="7/38";
round[7]="8/38";
round[8]="9/38";
round[9]="10/38";
round[10]="11/38";
round[11]="12/38";
round[12]="13/38";
round[13]="14/38";
round[14]="15/38";
round[15]="16/38";
round[16]="17/38";
round[17]="18/38";
round[18]="19/38";
round[19]="20/38";
round[20]="21/38";
round[21]="22/38";
round[22]="23/38";
round[23]="24/38";
round[24]="25/38";
round[25]="26/38";
round[26]="27/38";
round[27]="28/38";
round[28]="29/38";
round[29]="30/38";
round[30]="31/38";
round[31]="32/38";
round[32]="33/38";
round[33]="34/38";
round[34]="35/38";
round[35]="36/38";
round[36]="37/38";
round[37]="38/38";
$("#buttonholder").find("button").addClass("left")
$("#buttonholder").find("#submit").removeClass("left").addClass("right")
$("#buttonholder").find("#inputfield").addClass("right");
$("#displayround").text(round[0]);
Here is the next button function:
$("#next").click(function() {
$("#displayround").text()
});
}); //end of document.ready function
Any help appreciated!
I will store index in some location, such .data()
Initially
$("#displayround").text(round[0]).data('index', 0);
In function next function call fetch index and use it
$("#next").click(function() {
var index = +$("#displayround").data('index');
$("#displayround").text(round[index + 1]).data('index', index + 1);
});
Similarity, In previous method call
Note: You have take care array length
EDIT
do you have a solution similar to ojovirtual regarding the overflow? When it's at 38/38 I want it to go back to 1/38 and vice versa.
$("#previous").click(function () {
var index = +$("#displayround").data('index') - 1;
if (index <= 0) index = round.length - 1;
$("#displayround").text(round[index]).data('index', index);
});
$("#next").click(function () {
var index = +$("#displayround").data('index') + 1;
if (index >= round.length) index = 0;
$("#displayround").text(round[index]).data('index', index);
});
DEMO
You can add a hidden field with the value you are showing and update it every time the user clicks "next" or "previous":
<input type='hidden' name='actualValue' value='0'/>
And then in your javascript:
$("#next").click(function() {
var actualValue=parseInt($("input[name=actualValue]").val());
$("#displayround").text(round[actualValue]);
actualValue++;
if (actualValue >= round.length) //check for overflow
actualValue=0;
$("input[name=actualValue]").val(actualValue);
});
Note that if the user keeps clicking the "Next" button, we set the value to '0', so next to 38/38 it will show 1/38 again. The "previous" click function will be very similar.

Categories

Resources