Questionnaire scoring based on User's score - javascript

I'm a total noob so pardon the errors. I am trying to create a script that returns a new score for User B based on User A's score depending on the results of a 5-point Likert scale questionnaire. Both are firstly inputs at the top of the page, then the questionnaire which changes User B's score is below. It should work like this:Firstly: User A Score = x User B score = yIt rounds User A's score to the nearest 50, then divides it by 50 to create a number we'll call z.E.g User A score = 442, it gets rounded to 450, then divided by 50 = 9.This new number is z. or z =x/50 (to the nearest whole number). Now based on the survey responses, if User A clicks "very poor", it takes the input data for User B's score and subtracts z from it. Then gives a new result below based on the result of the questionnaire after submission such that:Very poor = y-zPoor = y (doesn't change the score)Satisfactory = y+zGood = y+z+1Very good = y+z+2Let me know if this makes sense. I attached a sample code I tried making below but I'm sure it's wrong. It needs to do more than this but this is the bare minimum I want to figure out. Thanks
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>
Questionnaire mess around
</h1>
<p>
<label for='ascore' class="inlinelabel">User A Score</label>
<input id="ascore" type="number"> <br>
<br>
<label for='bscore' class="inlinelabel">User B Score</label>
<input id="bscore" type="number">
</p>
<form action="" id="scorecalc" onsubmit="return false;">
<fieldset>
<br>
<legend>Peer Review Questionnaire!</legend>
<h3> Based on your recent project together, how would you rate User B in the following Skills</h3>
<hr>
<label ><strong>Time Management</strong></label>
<br>
<br>
<input type="radio" name="tmscore" value="tmvpoor" />
Very Poor
<input type="radio" name="tmscore" value="tmpoor"/>
Poor
<input type="radio" name="tmscore" value="tmsat" />
Satisfactory
<input type="radio" name="tmscore" value="tmgood"/>
Good
<input type="radio" name="tmscore" value="tmvgood" />
Very Good
<br>
<button onclick="myFunction()" class="button">Submit</button>
</fieldset>
</form>
<h2>
User B New Score </h2>
<p id="result"></p>
<script>
var theForm = document.forms["scorecalc"];
var x = document.getElementByID(ascore).value
var y = document.getElementByID(bscore).value
function closest50(x) {
return Math.round(x/ 50) * 50
}
var z = closest50(x)
var tm_result = new Array();
tm_result["tmvpoor"]=y-z;
tm_result["tmpoor"]=y;
tm_result["tmsat"]=y+z;
tm_result["tmgood"]=y+z+1;
tm_result["tmvgood"]=y+z+2
function myFunction() {
document.getElementById("result").innerHTML = tm_result;
}
</script>
</body>

There is a lot of problems in your code
things that should be inside of function are not
you don't really want an array but object to store key/value pairs
value of input fields is always string, you need to convert it to number before doing mathematical operations with it
document.getElementByID is not a function you want ...ById
you have said that you want to divide x by 50 but you immediately multiply it by 50 back to the original
ascore and bscore in your document.getElementById should be strings
you want to pass string to .innerHTML not an array/object
Here is working code. If you have some questions about it, post a comment below (I have changed only the JS part).
const theForm = document.querySelector('#scorecalc');
function closest50(x) {
return Math.round(x / 50);
}
function myFunction() {
const x = Number(document.getElementById('ascore').value);
const y = Number(document.getElementById('bscore').value);
const choice = document.querySelector('input[type=radio]:checked').value;
const z = closest50(x)
const tm_result = {
tmvpoor: y - z,
tmpoor: y,
tmsat: y + z,
tmgood: y + z + 1,
tmvgood: y + z + 2
};
document.getElementById("result").innerHTML = tm_result[choice];
}
<h1>
Questionnaire mess around
</h1>
<p>
<label for='ascore' class="inlinelabel">User A Score</label>
<input id="ascore" type="number"> <br>
<br>
<label for='bscore' class="inlinelabel">User B Score</label>
<input id="bscore" type="number">
</p>
<form action="" id="scorecalc" onsubmit="return false;">
<fieldset>
<br>
<legend>Peer Review Questionnaire!</legend>
<h3> Based on your recent project together, how would you rate User B in the following Skills</h3>
<hr>
<label ><strong>Time Management</strong></label>
<br>
<br>
<input type="radio" name="tmscore" value="tmvpoor" />
Very Poor
<input type="radio" name="tmscore" value="tmpoor"/>
Poor
<input type="radio" name="tmscore" value="tmsat" />
Satisfactory
<input type="radio" name="tmscore" value="tmgood"/>
Good
<input type="radio" name="tmscore" value="tmvgood" />
Very Good
<br>
<button onclick="myFunction()" class="button">Submit</button>
</fieldset>
</form>
<h2>User B New Score </h2>
<p id="result"></p>

Related

How to add error message alertbox in the given code?

<html>
<head>
<script type="text/javascript">
function gcd()
{
var x,y;
x=parseInt(document.myform.n1.value);
y=parseInt(document.myform.n2.value);
if((x>'a' && x<='z') && (y>'a' && y<='z') && (x>'A' && x<='Z') && (y>'A' && y<='Z'))
{
while(x!=y)
{
if(x>y)
x=x-y;
else
y=y-x;
}
document.myform.result.value=x;
}
else
{
alert("Enter valid character ! ");
}
</script>
</head>
<body>
<h1 align="center"><b>gcd of two numbers</b></h1>
<hr color="black">
<center>
Enter two numbers :
<form name="myform">
Number 1 : <input type="text" name="n1" value=""> <br> <br>
Number 2 : <input type="text" name="n2" value=""> <br> <br>
<input type="button" value="Get GCD" onClick="gcd()"> <br> <br>
GCD is : <input type="text" name="result" value="">
</form>
</body>
</html>
The above is an HTML-javascript code but I am trying to add a feature which would pop up an alert box if you enter a special character.Please help me figure out why the above code is not working .I'm a beginner at javascript and need your help.
Thanks in advance :)
Simply do with Change the input type with number .Its only allow the number
function gcd() {
var x, y;
x = document.myform.n1.value;
y = document.myform.n2.value
x = parseInt(x);
y = parseInt(y)
if (x > y) {
x = x - y;
} else {
x = y - x;
}
document.myform.result.value = x;
}
<h1 align="center"><b>gcd of two numbers</b></h1>
<hr color="black">
<center>
Enter two numbers :
<form name="myform">
Number 1 : <input type="number" name="n1" value=""> <br> <br> Number 2 : <input type="number" name="n2" value=""> <br> <br>
<input type="button" value="Get GCD" onClick="gcd()"> <br> <br> GCD is : <input type="number" name="result" value="">
</form>
The best way to not only handle errors but make sure that the text is in the desired format would be to use Regular Expression. Basic validation here could be done as said below by setting input type to number, although is not recommended.
You can always handle errors by Javascript Error Handling.
Would recommend doing more research on the following for your use case and figure out what your ideal case would be. Hope this helps !

Keeping a running total with Javascript in a span element

I'm trying to write a piece of code that is supposed to keep a running total. More specifically what I would like it to do is, every time you click the button to add the sub total to the total, it should keep adding into the subtotal. The way the whole thing works now is, there is three meal items to choose from in a dropdown that each have their own price. When a food item is selected, the user types in how many of that item they want. Then user clicks the add to total button to add the food item to one text field. Under that field is a span that shows the grand total after a $3.50 delivery charge is added on. The span is where I want the running total to keep adding the sum every time the button is clicked. I am new to Javascript so I've been trying my best. I've also looked at topics here on SO to see if I can find something similar to my issue and I've seen some that are close but not quite what I'm looking for. Here"s my code...
<script>
function myTotal()
{
var meals = document.getElementById("foodItems").value;
var howMany = document.getElementById("itemTotal").value;
var shippingCost = "3.50";
var totalBill = parseFloat(meals) * howMany + parseFloat(shippingCost);
var addingTotal = parseFloat(meals) * howMany;
var runTotal = document.getElementById("runningTotal").value;
if (isNaN(totalBill)) { // Cash calculator
document.getElementById("total").value = "Invalid amount"
//alert("result of isNaN" ); //The input amount is a non numeric string. It is or contains letters and/or spaces
}
else { //adds total to the sub total field
document.getElementById("total").value = "$" + parseFloat(addingTotal).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//Convert input value into a floating point number. toFixed() requires a number value to work with
}//end Cash Calculator
var i = ""; //This piece is where I'm trying to begin the running total
if(i=totalBill, i=howMany*totalBill, i++ ){//adds delivery charge + subtotal. But doesn't keep a running total
document.getElementById("runningTotal").innerHTML = parseFloat(totalBill).toFixed(2);
}
else {
document.getElementById("runningTotal").innerHTML = parseFloat(i++) * howMany;
}
}
</script>
<form id="survey" name="survey" method="get" action="formHandler.php" class="col-4">
<!-- enter your forms code below -->
<div id="fieldset">
<legend>Place an Order!</legend>
<h3>There is a $3.50 delivery fee</h3>
<fieldset>
<label for="foodItems">Quick Meal Food Items</label>
<select name="foodItems" id="foodItems">
<option value="6.00">Pepperoni Pizza - $6.00</option>
<option value="3.00">Bacon BBQ Burger - $3.00</option>
<option value="8.00">Steak and Eggs - $8.00</option>
</fieldset>
<!--The "input" element has "required" in the parameters so the user must fill out all fields but the email.-->
<fieldset>
<input type="text" name="itemTotal" id="itemTotal" size="25" required>How Many Orders?(Limit To 5 per Meal Type)</input>
</fieldset>
<fieldset>
<input type="button" name="click" id="button" value="Add to Order" onClick="myTotal()">
<input type="text" name="total" id="total" size="25">Grand Total</input>
<br>
<span id="runningTotal"></span> <!--runningTotal span-->
</fieldset>
<label for="name">Name: (First, Last)</label>
<input type="text" name="name" id="name" size="25" required></input>
<label for="Address">Address</label>
<input type="text" name="Address" id="address" size="25" required></input>
<label for="email">Email</label>
<input type="email" name="email" id="email" size="40" maxlength="40"></input>
<br><br>
<label for="checkbox">Sign me up for deals via email</label>
<input type="checkbox" name="checkbox" id="checkbox" value="Signup" checked="checked"></input>
<input type="submit" method="post" value="Submit" class="button"/>
<input type="reset" value="Reset" class="button"/>
</form>
</div>
Any help would be awesome! Please address any confusion please. I want to be as clear as possible to try to get the best help for me and others here on SO. I also hope my question isn't off topic. Like I said, I tried to find something pertaining to this here on SO. Thank you so much!
Do you mean something like this? (jsfiddle here)
function myTotal()
{
// Error checking removed....
// Calculate cost of current item
var itemSelect = document.getElementById("foodItems");
var mealCost = parseFloat(itemSelect.value);
var howMany = parseInt(document.getElementById("itemTotal").value);
var thisItemCost = mealCost * howMany;
var shippingCost = 3.5;
// Get running total from the "total" text box
var runTotal = parseFloat(document.getElementById("total").value);
// Only add shipping cost once
if (isNaN(runTotal) || 0 == runTotal) runTotal = shippingCost;
// Add this item to total and update "total" text box
document.getElementById("total").value = (thisItemCost + runTotal).toFixed(2);
// Add item to span
document.getElementById("runningTotal").innerHTML += "</br>" +
itemSelect.options[itemSelect.selectedIndex].innerHTML +
" x " + howMany +
" .... $" + thisItemCost.toFixed(2);
}

Calculate data based on text box values with javascript/html

I am trying to get the values from 3 html text fields and add them together to get the total value when the use clicks on the button. I am new to javascript and after researching online, I found an example code and implemented to my code, but it is not showing any values. Here is my code:
<form name="selectVehicleForm" action="SelectVehicle">
Car Make: <input type="text" name="make" id="make" value="${Vehicles.make}" disabled> <br>
Car Model: <input type="text" name="model" id="model" value="${Vehicles.model}" disabled> <br>
Car Year: <input type="text" name="year" id="year" value="${Vehicles.year}" disabled> <br>
Car Transmission: <input type="text" name="transmission" id="transmission" value="${Vehicles.transimssion}" disabled> <br>
Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="${Vehicles.ratePerMile}" disabled> <br>
Car Rate: <input type="text" name="rpd" id="rpd" value="${Vehicles.ratePerDay}" disabled> <br>
<%
int id = (Integer) request.getAttribute("id");
%>
<input type="hidden" name="id" value="<%=id%>">
Pick Up Date: <input type="date" name="pickUpDate"> <br>
Return Date: <input type="date" name="returnDate"> <br>
Total Miles: <input type="text" name="totalMile" id="totalMile" placeholder="approximate"> <br> <br>
<script>
function totalDue(){
var rpm = document.getElementById("rpm").value;
var rpd = document.getElementById("rpd").value;
var totalMiles = document.getElementById("totalMile").value;
var totalDue = (rpm * totalMiles) + rpd;
document.getElementById("totalDue").innerHTML = totalDue;
}
</script>
<br>Total Amount Due: <input type="text" name="totalDue" id="totalDue"> <br>
</form>
<button id="showPaymentForm" onclick="totalDue()">Billing/Payment Info</button>
You need to set the value of the field instead of innerHTML in your case. Please refer to the fiddle here : https://jsfiddle.net/jhf18hsr/1/
I have put the parsing to integer values, which you can change to float as per your need, when reading the values from input controls.
function totalDue(){
var rpm = parseInt(document.getElementById("rpm").value) || 0;
var rpd = parseInt(document.getElementById("rpd").value) || 0;
var totalMiles = parseInt(document.getElementById("totalMile").value) || 0;
var totalDue = (rpm * totalMiles) + rpd;
document.getElementById("totalDue").value = totalDue;
}
First we put some values in both rpm and rpd, like 3 and 40. For now let us do this:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm" value="3"> <br>
Or you can simply remove the default values if desired:
Car Rate Per Mile: <input type="text" name="rpm" id="rpm"> <br>
Same for rpd. In the future you may want to load this values from a database or something, it would be awesome since you stated you are new to JS and maybe you will try php later but not the case today; in the meantime remove the "disabled" part and input your desired values each time.
Second, add a parseFloat in your math so js treat your rpm and rpd values as numbers not as text; parseFloat will allow you to use and display some decimals, in contrast to parseInt.
var totalDue = (parseFloat(rpm) * parseFloat(totalMiles)) + parseFloat(rpd);
Third, change document.getElementById("totalDue").innerHTML = totalDue; for document.getElementById("totalDue").value=totalDue;. This way you will populate your output textbox onClick.
However this does not integrate dates into equation, you must ellaborate your JS function a little bit more to achieve this.
In your output textbox line I would add disabled since I don't want to write in this box, only show the result:
<br>Total Amount Due: <input type="text" name="totalDue" id="totalDue" disabled> <br>
Hope this helps.

Multiply form value by X and display total in html

<form>
Chapter 1 - Please enter how many copys you would like <br>
<input type="text" id="chap1"> <br><br>
Chapter 2 - Please enter how many copys you would like <br>
<input type="text" id="chap2"> <br><br>
Chapter 3 - Please enter how many copys you would like <br>
<input type="text" id="chap3"> <br><br>
Chapter 4 - Please enter how many copys you would like <br>
<input type="text" id="chap4"> <br><br>
Chapter 5 - Please enter how many copys you would like <br>
<input type="text" id="chap5"> <br><br>
<b> Total price : <output id = "total"> 0 </output> </b>
I'm trying to create a website in which you can order books by chapters, each chapter costs £2. I need it to multiply the value of the individual forms by 2 and then display this cost in the output. I would like to use java script in order to do this rather than jQuery.
I havent tried much as of yet as i cant find much on the subject, so any pointers in the right direction would be appreciated.
Thanks
function calc(){
price = 2;
fields = document.querySelectorAll("input[id^='chap']");
tot = 0;
for(i=0; i<fields.length; i++){
tot += fields[i].value * price;
}
document.getElementById("total").innerHTML = tot;
}
This is a simple example, you can improve it
fiddle link
<input type="text" id="chap1">
<input type="text" id="chap2">
<input type="text" id="chap3">
<input type="text" id="chap4">
<input type="text" id="chap5">
<b> Total price : <output id = "total"> 0 </output> </b>
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
var text1= document.getElementById("chap1").value;
var text2= document.getElementById("chap2").value;
var text3= document.getElementById("chap3").value;
var text4= document.getElementById("chap4").value;
var text5= document.getElementById("chap5").value;
var total=parseInt(text1)+parseInt(text2)+parseInt(text3)+parseInt(text4)+parseInt(text5);
document.getElementById("total").innerHTML = total*2.1;
}
</script>

Simple Gallon Calculator

I'm attempting to build a simple web form that takes 3 number inputs and outputs one number based on this formula: (a*b*c)/271).
This is the code I have but nothing is displayed in the output.
Clearly I have almost no clue what I'm doing.
I appreciate all help:
<body>
<img id="logo"src="images/a&l.png" alt="A&L Cesspool"/>
<h1>Grease Trap Gallon Calculator<h2>
<form name=calculator">
<input label="length" type="number" id="a">
<input label="width" type="number" id="b">
<input label="height" type="number" id="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6" >
</form>
<script language="JavaScript" type="text/javascript">
<!--
function gallons() {
var LENGTH = document.calculator.a.value;
var WIDTH = document.calculator.b.value;
var HEIGHT = document.calculator.c.value;
var Total =(LENGTH*WIDTH*HEIGHT)/271;
document.calculator.OUTPUT.value = Total;
}
// -->
</script>
document.forms.calculator. There's no such thing as document.calculator. Also, form elements need name attributes to refer to them in form context, not IDs.
In other news
You have unclosed quotes
You have irregular naming conventions (OUTPUT, a, Total)
You have irregular quotes policy (sometimes you have, sometimes you don't).
So basically
<form name="calculator">
<input label="length" type="number" name="a">
<input label="width" type="number" name="b">
<input label="height" type="number" name="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6">
</form>
function gallons() {
var LENGTH = document.forms.calculator.a.value;
var WIDTH = document.forms.calculator.b.value;
var HEIGHT = document.forms.calculator.c.value;
var Total = (LENGTH * WIDTH * HEIGHT) / 271;
document.forms.calculator.OUTPUT.value = Total;
}
Please grab a proper tutorial from MDN or some similar good source, and start reading.
Your call to document.calculator is not finding the element because its looking by id
change your form definition and it will work
<form name="calculator" id="calculator">

Categories