javascript/jquery survey progress bar - javascript

I'm trying to have a progress bar advance every time a user answers a question (even with multiple questions on a page). So I set up to variables at the beginning/top of the page:
<div id="progress"><p id="counter"><span id="percent">0%</span></p></div>
<script>var count = 0;
var total = 79;
var progress = 0;</script>
Then I do a bit of jQuery for most of the questions with radio inputs, and they work fine (and don't increase count if you change your option on the question). However, with checkboxes and selects, it's not working as well:
$('input[name="race"]').one("click", function(){
var n = 0;
if (n==0) {
n = ++n;
count = ++count;
progress = count/total;
$("#counter").css("width", progress);
$("#percent").text(progress + "%")
}
});
If I remove the if-statement, the function works, but it increases count for each checkbox.
I would also like to trim progress to just 3 characters, but it doesn't like progress = progress.slice(0,3); or `progress = progress.substr(0,10)

For the if statement it needs another = sign. That should get the logic right. Oh and you set n as a string in the line above, but compare it to an int in the line below. You will need to choose one or the other. From the line n=n++ I believe you will want to change var n = 0; instead of var n ="0";
Then for the progress variable you are trying to take the substr of an int. Thus you would need to convert the int to a string before trimming. But as an int it shouldn't need to be trimmed anywise.

Assuming that you have only radio buttons, checkboxes and selects. This should do the trick
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script>
var progress = 0;
//need this to check if the question has not been answered before
var questions = {
"pref1": 0,
"pref2":0,
"pref3":0
}
$( function() {
$("#progress").text(progress)
$("input, select").change( function() {
el_name = $(this).attr("name");
switch (this.nodeName.toLowerCase()) {
case "select":
field =$("[name='"+el_name+"']");
val = (field.val() === "" || !field.val()) ? null: field.val();
break;
case "input":
field =$("[name='"+el_name+"']:checked");
val = field.length;
break;
}
if (val) {
if (!questions[el_name]) {
progress = progress +1;
questions[el_name]=1
}
} else {
questions[el_name]=0
progress = (progress > 0)?progress-1:0;
}
$("#progress").text(progress)
})
})
</script>
<div id="progress">
</div>
<input type="radio" name="pref1" value="one">
one
<input type="radio" name="pref1" value="two">
two
<br>
<select name="pref2">
<option value="">Please select</option>
<option value="2">2</option>
</select>
<br>
<input type="checkbox" name="pref3" value="one">
one
<input type="checkbox" name="pref3" value="two">
two

Related

Is there a javascript function that I can make to give radiobuttons a value?

So I have a small issue with getting some values on radiobuttons. I've made a foreach loop in where the html makes radiobuttons. These are Yes/No buttons and Each yes/no set needs a value.
Like question 1 will have value 1, 2 will have 2, 3 will have 4, 4 will have 8 etc.
In the end it needs to add up to a total score, BUT if NO is selected (eg. question 4 with value of 8 is NO, then the value becomes 0)
Ive tried doing a Javascript function shown below that makes it sort of work. But if all answers are NO and you make question 4 YES(which should have a value of 8) then it just says that my value is 2. I knew that this wouldnt work but I'm wondering if I can change this in a way that I can make it work the way that I want to
#foreach (var item in Model)
{
<div class="box">
<p>#Html.DisplayFor(modelItem => item.Question)</p>
<label>
<input id="yes" type="radio" name="#item.Id" checked="">
<span class=" yes randobtn">Ja</span>
</label>
<label>
<input id="no" type="radio" name="#item.Id">
<span class="no randobtn">Nee</span>
</label>
</div>
}
<button class="btn btn-primary" onclick="GetCount()">check</button>
#section Scripts{
<script type="text/javascript">
$(document).on('click',
'#btn',
function() {
console.log('test');
location.href = "/Symptom/GetProblems?TotalPoints=" +
count;
});
var count = 1;
$(document).on('click',
'.randobtn',
function() {
GetCount();
});
function GetCount() {
var checkedRadioBtns = $('input[type="radio"]:checked');
count = 1;
for (var i = 0; i < checkedRadioBtns.length; i++) {
if (checkedRadioBtns[i].id === 'no') {
console.log('in de if');
continue;
} else {
count = count * 2;
}
}
alert(count);
}
</script>
}
This is what I want: http://prntscr.com/o6zrqd
But as you can see in the alert it just says 1 when NO is selected
put value of true and false in the array
and then
value="#item.true_value"

Reveal additional info based on two (out of three) checkboxes JavaScript

I'm new at Javascript and I'm trying to reveal additional info only if any 2 out of 3 checkboxes are checked.
Here is my code so far (I'm trying to enter my code in the question but It's not working, sorry. I also may have made it more complicated then necessary, sorry again). I did place my code in the Demo.
<script>
var checkboxes;
window.addEvent('domready', function() {
var i, checkbox, textarea, div, textbox;
checkboxes = {};
// link the checkboxes and textarea ids here
checkboxes['checkbox_1'] = 'textarea_1';
checkboxes['checkbox_2'] = 'textarea_2';
checkboxes['checkbox_3'] = 'textarea_3';
for ( i in checkboxes ) {
checkbox = $(i);
textbox = $(checkboxes[i]);
div = $(textbox.id + '_container_div');
div.dissolve();
showHide(i);
addEventToCheckbox(checkbox);
}
function addEventToCheckbox(checkbox) {
checkbox.addEvent('click', function(event) {
showHide(event.target.id);
});
}
});
function showHide(id) {
var checkbox, textarea, div;
if(typeof id == 'undefined') {
return;
}
checkbox = $(id);
textarea = checkboxes[id];
div = $(textarea + '_container_div');
textarea = $(textarea);
if(checkbox.checked) {
div.setStyle('display', 'block');
//div.reveal();
div.setStyle('display', 'block');
textarea.disabled = false;
} else {
div.setStyle('display', 'none');
//div.dissolve();
textarea.value = '';
textarea.disabled = true;
}
}
<label for="choice-positive">
<script type="text/javascript">
function validate(f){
f = f.elements;
for (var c = 0, i = f.length - 1; i > -1; --i)
if (f[i].name && /^colors\[\d+\]$/.test(f[i].name) && f[i].checked) ++c;
return c <= 1;
};
</script>
<label>
<h4><div style="text-align: left"><font color="black">
<input type="checkbox" name="colors[2]" value="address" id="address">Full Address
<br>
<label>
<input type="checkbox" name="colors[3]" value="phone" id="phone">Phone Number <br>
<label>
<input type="checkbox" name="colors[4]" value="account" id="account">Account Number <br>
</form>
<div class="reveal-if-active">
<h2><p style = "text-decoration:underline;"><font color="green">Receive the 2 following
pieces of info:</h2></p>
</style>
Sorry i wasn't able to exactly use the code you provided but tried to change just enough to get it working.
I've uploaded a possible solution to JSFiddle - you essentially can add event listeners to the checkboxes that recheck when clicked how many are selected and show/hide via removing/adding a class e.g. additionalContactBox.classList.remove('reveal-if-active');

How can I select radio button values through for loop in JavaScript?

I'm writing a form for a personality test. The page has questions where the user would need to choose an answer for each. The page will not allow the user to skip questions and it will alert them to answer the missing questions. When the form is submitted, the page will show the score.
I'm trying to store the values of radio buttons in an array using a for loop. It is not working.
Here is the HTML code:
<!-- Form -->
<form name="quiz" onsubmit="return show()">
<!-- Question 1 -->
<p>Question 1</p>
<input type="radio" name="q0" value="a"> a
<br>
<input type="radio" name="q0" value="b"> b
<br>
<input type="radio" name="q0" value="c"> c
<!-- Question 2 -->
<!-- Question 3 -->
<!-- Question 4 -->
<!-- Question 5 -->
<p>Question 5</p>
<input type="radio" name="q4" value="a"> a
<br>
<input type="radio" name="q4" value="b"> b
<br>
<input type="radio" name="q4" value="c"> c
<!-- Submit Button -->
<input type="submit" value="Show Result">
</form>
Here is my JavaScript code:
function show() {
var questions = 5;
var score = 0;
var solution = ["a", "c", "a", "b", "b"];
var answers = [];
for (i = 0; i < questions; i++) {
answers[i] = document.quiz.eval('q' + i).value;
if (answers[i] == null || answers[i] == '') {
window.alert("You need to answer question " + (i + 1));
return false;
}
if (solution[i] == answers[i]) {
score++;
}
}
window.alert(score);
}
eval is a property of window object and not the form , but in fact you don't actually need to use it.
Solution 1. replace
answers[i] = document.quiz.eval('q'+i).value;
with
var tmp = 'q'+i;
answers[i] = document.quiz[tmp].value;
Solution 2. replace
answers[i] = document.quiz.eval('q'+i).value;
with
document.quiz['q'+i].value;
NOTE: Even if you could use eval like the way you wanted (using prototypes) it would still give error because on this line
answers[i] = document.quiz.eval('q'+i).value;
suppose i=0 eval would try to evaluate q0 (treating it as a named variable) and you don't have any variable with that name in your global scope
You need to loop through each of the radio button options for each radio group to find the checked input and get it's value. At the moment you are just looping through each group.
Add this at the beginning of your for loop:
var radioButtons = document.getElementsByName("q"+i);
for (var x = 0; x < radioButtons.length; x ++) {
if (radioButtons[x].checked) {
answers[i] = radioButtons[x].value;
}
}
What you need is a validating function.
// Since you mentionned
// "I'm trying to store the values of radio buttons in an array"
var answers = [];
var show = (function(answers) {
// evaluate this once and avoid globals
var questions = 5,
solution = ["a", "c", "a", "b", "b"],
form = document.quiz;
// and return a validate function
return function() {
var score = 0,
success = solution.every(function(value, i) {
// get the value of the form field, notice the brackets
var current = answers[i] = form['q' + i].value;
if (current === value) {
score++;
} else if (current == null || current == '') {
alert("You need to answer question " + (i + 1));
return false;
}
return true;
});
if (success) alert("Score: " + score);
return success;
};
})(answers);
The important part is document.quiz['q' + i]. See Get Radio Button Value with Javascript.

Javascript calculation returns 'on' when calculating percentage of variable

I constructed a calculation form out of different modules and got it to work except for 1 element.
The overall calculation is build up as (value + value = total), and the values are all regular numbers.
However, the last bit I added is a 'percentage'-value which is 10% of the first value in the form. So as an example:
Value 1 = 50,
Percent value 2 = 5 (10% of value 1),
Total = 55
In my code this looks as follows:
var NonTrans_prices = new Array();
NonTrans_prices["NoneNon"] = 0;
NonTrans_prices["LemonNon"] = 5994;
NonTrans_prices["CustardNon"] = 7076;
function NonTrans() {
var NonTransPrice = 0;
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
NonTransPrice = NonTrans_prices[selectedFilling.value];
return NonTransPrice;
}
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
function optionprice1() {
var inscriptionPrice = 0;
var theForm = document.forms["GRANADANEO"];
var optionprice = theForm.elements["optionprice"];
if (optionprice.checked == true) {
inscriptionPrice = optionprice.value;
}
return inscriptionPrice;
}
function calculateTotal() {
var cakePrice = NonTrans() + optionprice1();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price: " + cakePrice + " \u20ac";
}
*The NonTransPrice is connected to a dropdown box, and the optionprice1 is connected to a checkbox.
As soon as I tick the checkbox containing the 10% value, the letters "on" are added to the total price. What's going wrong?
**Sorry forgot to post the entire code so that you guys/girls can test: https://jsfiddle.net/6a55tm4j/
For some reason it doesn't show the total value in jsfiddle, on the live website I am testing on it does so that's not really a problem I am facing live.
Live link: http://axesseurope.be/appalacarte/Calculator/axess_calculator.html
This is the HTML code containing the parts affected by the .js code:
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="GRANADANEO" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<table><tr><td>
<label >NonTrans</label>
<select id="NonTrans" name='NonTrans' onchange="calculateTotal()">
<option value="NoneNon">Select Dimensions</option>
<option value="LemonNon">3,00 6,40 0,85</option>
<option value="CustardNon">3,00 7,50 0,85</option>
</select>
</td></tr></table>
<hr>
<br/>
<label>Granada Neo Opties Algemeen</label>
<p>
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
<label for='optionprice' class="inlinelabel">optionprice</label>
</p>
<p>
<input type="checkbox" id="SchuifdeurVoorzijde" name='SchuifdeurVoorzijde' onclick="calculateTotal()" />
<label for='SchuifdeurVoorzijde' class="inlinelabel">Schuifdeur in voorzijde</label>
</p>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
In the end with the help of Scott Marcus this was the solution:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var theForm = document.forms["GRANADANEO"];
var selectedFilling = theForm.elements["NonTrans"];
var lstNonTransValue = NonTrans_prices[selectedFilling.value];
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[selectedFilling.value];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
Checkboxes have a value of "on" when they are selected. Ensure that your checkboxes include a value attribute that contains the meaningful data they represent. For example:
<input type="checkbox" id="chkSomeId" name="chkSomeID"
value="someValueToBeWhenChecked">
This is true of radio buttons as well.
So, in your code, this line:
inscriptionPrice = optionprice.value
is most-likely accessing the value of either a checkbox or radio button that does not have an explicit value set for it, but is checked.
Also, remember that all values pulled from HTML come into JavaScript as strings, so if you need to do math with those values, you'll want to use parseInt() and parseFloat().
UPDATE: now that you have posted your HTML, I see this:
<input type="checkbox" id="optionprice" name='optionprice' onclick="calculateTotal()" />
which is exactly what I suspected. My above answer will correct the problem. That checkbox needs a value set for it.
UPDATE:
In your following code:
//Add percentage
var price = NonTrans_prices;
var percentage = 10;
var costs = (price * percentage) / 100;
var optionprice = price + percentage;
//Add percentage
function optionprice1()
{
var inscriptionPrice=0;
//Get a refernce to the form id="GRANADANEO"
var theForm = document.forms["GRANADANEO"];
//Get a reference to the checkbox id="optionprice"
var optionprice = theForm.elements["optionprice"];
//If they checked the box set inscriptionPrice to 20
if(optionprice.checked==true){
inscriptionPrice=optionprice.value;
}
//finally we return the inscriptionPrice
return inscriptionPrice;
}
I think that you should take the 4 var lines and include them in the function.
I think that the first line: var price = NonTrans_prices; is incorrect, because it sets the variable price to the actual array of NonTrans prices, rather than looking up a particular price, which would be:
var price = NonTrans_prices[document.getElementById("nonTransList").value];
Then, your problem is that if the optionPrice checkbox is checked, you are trying to access the value of the checkbox, which (as I've said) doesn't explicitly exist, so you get "on" (because the checkbox is checked). What you should be doing is setting the price to result of the 10% calculation that was just done on the line above. So the final function looks like this:
function optionprice1()
{
var chkOptionPrice = document.getElementById("optionprice");
var lstNonTransValue = document.getElementById(NonTrans).value;
var inscriptionPrice = 0;
if(optionprice.checked === true){
// Look up the price in the array that matches the dropdown list's value
var price = NonTrans_prices[lstNonTransValue];
// Do the math to calculate 10% of the original price
var percentage = 10;
inscriptionPrice = (price * percentage) / 100;;
}
// finally we return the inscriptionPrice
return inscriptionPrice;
}
You were close, but the thing that, I think, tripped you up was that you created a variable with the same name as your checkbox and after doing the calculation, you should have been trying to get the value of your variable, but you were trying to get the value of the checkbox, which isn't where the answer was.
I hope that I've understood what you wanted correctly, but even if my algorithm is off, I hope you can see that you don't want to be using the value of the checkbox to get your answer, since it doesn't store any value.

Add another condition to Show/Hide Divs

I have the follow script on a form.
jQuery(document).ready(function($) {
$('#bizloctype').on('change',function() {
$('#packages div').show().not(".package-" + this.value).hide();
});
});
</script>
Basically, depending on the value of the select box #bizloctype (value="1","2","3" or "4") the corresponding div shows and the rest are hidden (div class="package-1","package-2","package-3", or "package-4"). Works perfectly.
BUT, I need to add an additional condition. I need the text box #annualsales to be another condition determining which div shows (if the value is less than 35000 then it should show package-1 only, and no other packages.
I think the below script works fine when independent of the other script but I need to find out how to marry them.
<script>
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
else
{
$(".package-2").show();
}
});
</script>
Help please?
I would remove the logic from the anonymous functions and do something like this:
// handle display
function displayPackage( fieldID ) {
var packageType = getPackageType(fieldID);
$('#packages div').show().not(".package-" + packageType).hide();
}
// getting the correct value (1,2,3 or 4)
function getPackageType( fieldID ) {
// default displayed type
var v = 1;
switch(fieldID) {
case 'bizloctype':
// first check it annualsales is 1
v = (getPackageType('annualsales') == 1) ?
1 : $('#' + fieldID).val();
break;
case 'annualsales':
v = (parseInt($('#' + fieldID).val(),10) <= 35000) ? 1 : 2;
break;
}
return v;
}
jQuery(document).ready(function($) {
$('#bizloctype,#annualsales').on('change',function() {
displayPackage($(this).attr('id'));
});
});
If I understand your question properly, try this code out. It first adds an onChange listener to #annualsales which is the code you originally had. Then, for the onChange listener for #bizloctype, it simply checks the value of #annualsales before displaying the other packages.
jQuery(document).ready(function($) {
// Check value of #annualsales on change
$("#annualsales").change(function(){
$(".package-1,.package-2,.package-3,.package-4").hide();
var myValue = $(this).val();
if(myValue <= 35000){
$(".package-1").show();
}
// Only show other packages if value is > 35000
$('#bizloctype').on('change',function() {
$(".package-1,.package-2,.package-3,.package-4").hide();
if ($('#annualsales').val() <= 35000) {
$(".package-1").show();
} else {
$('#packages div').show().not(".package-" + this.value).hide();
}
});
});
Since you already use JQuery you can use the data() function to create a simple but dynamic condition system. For example, you could annotate each element with the required conditions and then attach change listeners to other elements to make the condition active or inactive for the elements.
For example, with this HTML:
<div id="conditions">
Condition 1: <input type="checkbox" id="check1" /> <= check this<br/>
Condition 2: <input type="checkbox" id="check2" /><br/>
Condition 3: <input type="text" id="value1" /> <= introduce 1001 or greater<br/>
Condition 4: <input type="text" id="value2" /><br/>
</div>
<p id="thing" data-show-conditions="check1 value1-gt-1000"
style="display: none;">
The thing to show.
</p>
And this Javascript:
function setShowCondition(el, condition, active) {
var conditions = $(el).data('conditions') || {};
conditions[condition] = active;
$(el).data('conditions', conditions);
var required = ($(el).data('show-conditions') || "").split(" ");
var visible = required.every(function (c) {
return conditions[c];
});
if (visible) {
$(el).show();
} else {
$(el).hide();
}
}
$("#conditions input[type='checkbox'").change(function () {
setShowCondition('#thing',
$(this).attr('id'),
$(this).is(':checked'));
});
$("#value1").change(function () {
var number = parseInt($(this).val());
setShowCondition('#thing', 'value1-gt-1000', number > 1000);
});
You can maintain conditions easily without having to nest and combine several if statements.
I've prepared a sample to show this in https://jsfiddle.net/2L5brd80/.

Categories

Resources