Comparing answer key array with input answers - javascript

This is my first day using HTML/Javascript. I've done some Java a while ago. I'm trying to make a quiz that will get answers from a drop down list and compare them to the answer key. I've tried so many things I can't even remember them all. Any help would be appreciated. Specifically, I cant figure out how to compare each element in the two arrays. I'm sure there is a lot more wrong than just the arrays. I;ve googled answers for 4 hours and got nothinggggg. Here is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.<p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width = 300 height = 200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
var q1 = document.getElementById("Q1");
var valueQ1=q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2=q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3=q3.options[q3.selectedIndex].value
var array ans = [1,2,3]
var array inpans = [valueQ1,valueQ2,valueQ3]
var counter = 0;
var count = 0;
function myFunc(){
while (count<ans.length){
if(ans[count]==inpans[count])
{
counter ++;
count ++;
}else {
counter = counter;
count ++,
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>

You have a number of issues which need fixing:
Your HTML is invalid. Your're not closing your <p> tag on line 11:
<p>Please match the letter to the corresponding answer.</p> <!-- <-- close this -->
You have many syntax errors in your code. Whenever your code isn't working, the first thing you should look for is syntax errors. Syntax errors can be identified by your brower's console. The first syntax errors are on lines 58 and 59. There should only be one variable name (identifier) after the var keyword:
var ans = [1, 2, 3]; // <-- used to be: var array ans
var inpans = [valueQ1, valueQ2, valueQ3]; // used to be: array inpans
Another syntax error occurs on line 70. Here you're using a comma instead of a semi-colon. Again, the console could of helped you identify this error yourself:
count++; // used to be: count++,
Your next issue is a logical issue. The following code runs when the page loads:
var q1 = document.getElementById("Q1");
var valueQ1 = q1.options[q1.selectedIndex].value
var q2 = document.getElementById("Q2");
var valueQ2 = q2.options[q2.selectedIndex].value
var q3 = document.getElementById("Q3");
var valueQ3 = q3.options[q3.selectedIndex].value
...as it runs when the page initially loads, the values of valueQ1 etc. will all be the initial value of the dropdowns when the page initially loads. These values don't change when you change the selected value in the dropdowns. If you wanted that behaviour you'd need an event listener. However, an easy way to fix this is to set the values of valueQ1 through to valueQ3 inside your function. This way, your code will grab the values from the dropdowns when you click your button, which should be after the user has manually selected a value from the dropdowns themselves:
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
...
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value; // you can just grab the dropdown's value, no need for `q1.options[q1.selectedIndex].value`
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
...
Fixing all these will allow your code to check against answers. Currently, as your count variable is defined outside of the myFunc, your button will only run your while loop once (as the second time it runs count >= ans.length, making your while loop condition false - thus not running the code within it). If you want users to have multiple attempts at a given question you define count inside your function so that it gets reset when the button is clicked.
As a side note, if you're planning on using this code in production keep in mind that users will be able to see the answers to the questions by inspecting your website's source.
See altered code below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br>
<br>
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width=300 height=200>
<br>
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br>
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br>
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br>
<br>
<button onclick="myFunc()">Click me</button>
<script>
// Get dropdown elements when page loads
var q1 = document.getElementById("Q1");
var q2 = document.getElementById("Q2");
var q3 = document.getElementById("Q3");
var ans = [1, 2, 3]
var counter = 0;
var count = 0;
function myFunc() {
// get value of dropdown elements
var valueQ1 = q1.value;
var valueQ2 = q2.value;
var valueQ3 = q3.value;
var inpans = [valueQ1, valueQ2, valueQ3];
while (count < ans.length) {
if (ans[count] == inpans[count]) {
counter++;
count++;
} else {
counter = counter;
count++;
}
}
document.getElementById("one").innerHTML = "You got " + counter + " right.";
}
</script>
<p id="one"></p>
</body>
</html>
For what it's worth, here's how I would write the equivalent code. It takes advantage of the class you have on each dropdown, and then iterating over all dropdowns to check whether they equal the correct answer. If you want the user to have multiple attempts at the question you can remove the {once: true} option:
// Get dropdown elements when page loads
const dropdowns = document.querySelectorAll('.Q');
const submitBtn = document.querySelector("#guess-btn");
const resultElem = document.getElementById("one");
const ans = [1, 2, 3];
submitBtn.addEventListener("click", () => {
const correctCount = [...dropdowns].reduce(
(total, dropdown, i) => total + (+dropdown.value === ans[i]), 0
);
resultElem.innerText = `You got ${correctCount} right.`;
}, {once: true});
<h1>Critical Device Test</h1>
<p>Please match the letter to the corresponding answer.</p>
<br />
<br />
<img src="https://i.imgur.com/kDHijRv.jpg" alt="Proton Source CD's" width="300" height="200" />
<br />
<label for="Q1">A:</label>
<select id="Q1" class="Q">
<option value="0">SELECT</option>
<option value="1">L:CRDEV</option>
<option value="2">L:CDC</option>
<option value="3">L:LINCDC</option>
<option value="4">L:LINAC</option>
</select>
<br />
<label for="Q2">B:</label>
<select id="Q2" class="Q">
<option value="0">SELECT</option>
<option value="1">n1</option>
<option value="2">n2</option>
<option value="3">n3</option>
<option value="4">n4</option>
</select>
<br />
<label for="Q3">C:</label>
<select id="Q3" class="Q">
<option value="0">SELECT</option>
<option value="1">e1</option>
<option value="2">e2</option>
<option value="3">e3</option>
<option value="4">e4</option>
</select>
<br />
<br />
<button id="guess-btn">Click me</button>
<p id="one"></p>

Related

Dependent and Dynamic Dropdown form in js

Hey so I am trying to to make both a dynamic and dependent dropdown form. Essentially I want the second form to be dependent of the first forms option, and when you add a new form field I want it to generate a new div form with a different ID and and the option in the first form removed from the second and then third form. In the case the user only selects on form and doesn't decide to add a second or a third, I would like to still submit a NULL value through the form's that aren't submitted. Js is not my strong suit so any help would be appreciated
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="nativelangdrop">
<option value="1">Fashion Designer</option>
<option value="2">Visual Artist</option>
<option value="3">Clothing reseller</option>
<option value="4">Musician</option>
<option value="5">Videographer</option>
<option value="6">Photographer</option>
<option value="7">Dancer</option>
<option value="8">Sculpter</option>
</select>
<span id="additional"></span>
<input id="addBtn" type="button" value=" + "/>
<hr />
<select id="genre">
<option value="1">Fashion Designer</option>
<option value="2">Visual Artist</option>
<option value="3">Clothing reseller</option>
<option value="4">Musician</option>
<option value="5">Videographer</option>
<option value="6">Photographer</option>
<option value="7">Dancer</option>
<option value="8">Sculpter</option>
</select>
<span id="additional2"></span>
<script>
var total;
// To auto limit based on the number of options
// total = $("#nativelangdrop").find("option").length - 1;
// Hard code a limit
total = 2;
//if total two hide plus button
$("#addBtn").on("click", function() {
var button = document.getElementById('addBtn');
var ctr = $("#additional").find(".extra").length;
var ctr2 = $("#additional2").find(".extra2").length;
if (ctr < total) {
var $ddl = $("#nativelangdrop").clone();
var $ddl2 = $("#genre").clone();
$ddl.attr("id", "ddl" + ctr);
// $ddl2.attr("id", "ddl2" + ctr);
$ddl.addClass("extra");
$ddl2.addClass("extra2");
$("#additional").append($ddl);
$("#additional2").append($ddl2);
}
else{
button.style.display = 'none';
}
});
//implement dependent genre form.
/*implement creating form after each iteration of ctr, var MyIDvariable = "MyID123";
var cartHTML = '<div id="'+MyIDvariable+'" class="soft_add_wrapper" onmouseover="setTimer();">';
... the rest of your code ... */
</script>
</body>
</html>```

How do I use the compute() event properly for a calculator

I'm trying to code a sample rate calculator and I need the compute() function to display text with certain parameters each time it's pressed, but it's not working
I'll paste the code samples below.
var principal = document.getElementById("principal").value;
var rate = document.getElementById("rate").value;
var years = document.getElementById("years").value;
var interest = principal * years * rate /100;
var year = new Date().getFullYear()+parseInt(years);
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = "If you deposit "+principal+",\<br\>at an interest rate of "+rate+"%\<br\>You will receive an amount of "+amount+",\<br\>in the year "+year+"\<br\>";
}
function checkdata() {
//create references to the input elements we wish to validate
var years = document.getElementById("years");
var principal = document.getElementById("Principal");
//Check if "No of Years" field is actual year
if (years.value != "year") {
alert("Please input the actual year");
years.focus();
return false;
}
//Check if principal field is zero or negative
if (principal.value == "0" || principal.value == "negativ no") {
alert("Enter a positive number");
principal.focus();
return false;
}
//If all is well return true.
alert("Form validation is successful.")
return true;
}
function updateValue(event) {
document.getElementById("rate_val").innerText = event.value;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
<title>Simple Interest Calculator</title>
</head>
<body>
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount"></label>
Amount <input type="number" id="principal">
<br/>
<br/>
<label for="Interest Rate"></label>
<label for="Interest Rate">Interest Rate</label>
<input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
<span id="rate_val">10.25%</span>
<br/>
<br/>
<label for="No. of Years"></label>
No. of Years <select id="years">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<!-- fill in the rest of the values-->
</select>
<br/>
<br/>
<label for="Compute Interest"></label>
<button onclick="compute()">Compute Interest</button>
<br/>
<br/>
<span id="result"></span>
<br/>
<br/>
</form>
<br/>
<br/>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
</body>
</html>
The main issue in your code is because you've attached the onclick attribute to the button which submits the form. As the form submission is not being prevented, the page is redirected before you can update the DOM.
To fix this, hook the event handler to the submit event of the form and call preventDefault() on the event which is passed to the handler as an argument.
In addition, there's some other issues in your code.
You should avoid using onX attributes as they are no longer good practice. Attach your event handlers using unobtrusive JS, such as addEventListener().
amount is not defined anywhere. You will need to declare and set this variable. I've used a dummy value for it in the code below.
You need to retrieve the value properties of your form controls when the button is clicked, not when the page loads. This is to ensure that the values the user enters are retrieved from the DOM.
Wrap the field controls and the label text within the label element. Leaving them empty serves no purpose.
Avoid using the <br /> tag as much as possible. Given the above change to your label elements, apply CSS to add the margin underneath them instead.
In the checkData() function, years is a selection of integer values, so comparing those values to a "year" string is redundant.
In addition, to detect a negative number compare it to < 0, not the string "negative no"
With all that said, try this:
let principalEl = document.querySelector("#principal");
let rateEl = document.querySelector("#rate");
let rateOutputEl = document.querySelector('#rate_val');
let yearsEl = document.querySelector("#years");
let formEl = document.querySelector('#form1');
let result = document.querySelector('#result');
let amount = '???';
formEl.addEventListener('submit', e => {
e.preventDefault();
if (!checkData())
return;
let principal = principalEl.value;
let rate = rateEl.value;
let year = yearsEl.value;
let interest = principal.value * years.value * rate.value / 100;
let endYear = new Date().getFullYear() + parseInt(years.value);
result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
});
rateEl.addEventListener('input', e => {
rateOutputEl.textContent = e.target.value + '%';
});
function checkData() {
let principal = principalEl.value;
if (!principal || parseFloat(principal) < 0) {
alert("Enter a positive number");
principalEl.focus();
return false;
}
return true;
}
label {
display: block;
margin-bottom: 20px;
}
form {
margin-bottom: 50px;
}
<div class="container">
<h1>Simple Interest Calculator</h1>
<form id="form1">
<label for="Amount">
Amount
<input type="number" id="principal">
</label>
<label for="Interest Rate">Interest Rate
<input type="range" id="rate" min="1" max="20" step="0.25" value="10.25" />
<span id="rate_val">10.25%</span>
</label>
<label for="No. of Years">
No. of Years
<select id="years">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<!-- fill in the rest of the values-->
</select>
</label>
<label for="Compute Interest">
<button type="submit">Compute Interest</button>
</label>
<span id="result"></span>
</form>
<footer>© Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer>
</div>
function compute()
{
var result = document.getElementById("result").value;
document.getElementById("result").innerHTML = ~If you deposit ${principal} at an ${interest} rate of ${rate}% You will receive an amount of ${amount} in the year ${year}~;
}

how to add multiple values to one option in a listbox javascript

Currently I have a listbox with apples, oranges and pears in it. Each one of those has a specific value. When the user makes a selection the corresponding value gets displayed on the page.
What I want to do is instead put two different values on each option. I want apples to have the value of 10000 and also 20000 and oranges 20000 and 50000 and pears 30000 and 20000, and I want to have two scenarios , one where when the user makes a selection and the first value gets displayed on the page and a second scenario where the second value gets displayed. I'm not sure how to do it ?
function test() {
var a = document.getElementById("listboxtest").selectedIndex;
var b = document.getElementById("listboxtest").options;
var c = (b[a].value);
document.getElementById("demo").innerHTML = c;
}
<p id="demo"></p>
<form>
<select id="listboxtest" onchange="test()">
<option value=10000> apples </option>
<option value=20000> oranges </option>
<option value=30000> pears </option>
</select>
<form>
do the below example,
var index = 0;
function test() {
var a = document.getElementById("listboxtest").selectedIndex;
var b = document.getElementById("listboxtest").options;
var c = (b [a].value.split(',')[index]);
document.getElementById("demo").innerHTML = c;
index = 0;
}
function test2() {
index = 1;
test();
}
test();
.button {
cursor:pointer;
border:1px solid grey;
padding:6px 12px;
background-color:#e8e8e8;
border-radius:5px;
}
#listboxtest {
padding:6px 12px;
border-radius:5px;
}
<p id="demo"></p>
<form>
<select id = "listboxtest" onchange = "test()">
<option value = '10000,20000'> apples </option>
<option value = '20000,50000'> oranges </option>
<option value = '30000,80000'> pears </option>
</select>
<span class="button" onclick="test2()">Change Value</span>
<form>
I have used a set radio buttons to check if it is a first or second value:
<form>
<p>Select your choice to display value:</p>
<div>
<input type="radio" id="choice1" name="val" value="0" onchange="test()">
<label for="choice1">First value</label>
<input type="radio" id="choice2" name="val" value="1" onchange="test()">
<label for="choice2">Second value</label>
</div>
<br>
<select id="listboxtest" onchange="test()">
<option value='10000|20000'> apples </option>
<option value='20000|50000'> oranges </option>
<option value='30000|20000'> pears </option>
</select>
<br><br>
Result: <p id="result"></p>
</form>
<script src="test.js"></script>
test.js:
function test() {
let a = document.getElementById("listboxtest").selectedIndex;
let b = document.getElementById("listboxtest").options;
let tokens = (b[a].value).split("|");
let x = document.querySelector('input[name="val"]:checked').value;
document.getElementById("result").innerHTML = tokens[x];
}
EDIT: Second Scenario
...what im trying to do now is , to just have one listbox and one button
. the first value gets called on the onchange and the second value
gets called when the user clicks the button. how could i do this ?
<body onload="test()">
<form>
<p>Select your choice or click button:</p>
<select id="listbox" onchange="test(this.id)">
<option value='apples'> apples </option>
<option value='oranges'> oranges </option>
<option value='pears'> pears </option>
</select>
<br><br>
<button id="button" type="button" onclick="test(this.id)">Press</button>
<br><br>
Result: <p id="result"></p>
</form>
<script src="test.js"></script>
test.js:
function test(elementId = 'formload') {
var selectionValues = [];
selectionValues['apples'] = {first: 10000, second: 20000};
selectionValues['oranges'] = {first: 20000, second: 50000};
selectionValues['pears'] = {first: 30000, second: 20000};
var listVal = document.getElementById("listbox").value;
var result = null;
switch(elementId) {
case 'formload': // same as selected value of list box
// this is when the page is refreshed
case 'listbox':
result = selectionValues[listVal].first;
break;
case 'button':
result = selectionValues[listVal].second;
break;
}
document.getElementById("result").innerHTML = result;
}

generating results using dropdown selections with javascript

This may come out very convoluted but I will try to keep it as clear as possible.
I am trying to to find out if its possible to have an simple html form. That has 3 drop-downs that have similar options for different variable, that I want to be able to then use in JavaScript functions to return a sum. Ultimately I am trying to keep this all local without having to submit the info to a server to return the answer but if that is the way I have to go I will try to figure it out.
Example: I have 3 drop-downs in a form. They are numberOfDice, sidesPerDice, and constMod; all three drop downs are loaded with numbers (no text strings) numberOfDice values= 1-10, sidesPerDice values = 4sides, 6sides, 8sides, upto 20sides, and constmod values are plus0, plus1, plus2 etc upto plus10, I believe that each individual option in the drop-down has to have its own unique value (correct me if I'm wrong)
the below is the HTML for the form/user interface. I don't have any JavaScript as of yet as I was not sure if this would even work with JavaScript or if I would have to use asp.net or php. (Currently not working on server side scripting, but hopefully soon).
Any insight into this would be much appreciated. Also if you can make any recommendations to the form/drop-down code is correct.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script src="Script.js"></script>
</head>
<body>
<form id="totalHitPoints">
<div class="w3-container w3-center w3-blue">
<h1>Monster Stat Generater</h1>
</div>
<div class="w3-container">
<p>Number of Dice:</p>
<select id="numberOfDice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="w3-container">
<p>Number of Sides per Dice</p>
<select id="sidesPerDice">
<option value="4sides">4</option>
<option value="6sides">6</option>
<option value="8sides">8</option>
<option value="10sides">10</option>
<option value="12sides">12</option>
<option value="20sides">20</option>
</select>
</div>
<div class="w3-container">
<p>Constitution Modifier</p>
<select id="constMod">
<option value="plus0">0</option>
<option value="plus1">1</option>
<option value="plus2">2</option>
<option value="plus3">3</option>
<option value="plus4">4</option>
<option value="plus5">5</option>
<option value="plus6">6</option>
<option value="plus7">7</option>
<option value="plus8">8</option>
<option value="plus9">9</option>
<option value="plus10">10</option>
</select>
</div>
<br>
</form>
<button id="form_submit" type="submit">Get Hit Points</button>
<div class="w3-container" style="width:128px;">
<p>Total Hit Points:</p>
<p id="getHitPoints"class="w3-border w3-center w3-padding" style="width: 64px;">0</p>
</div>
</body>
I don't think that i was clear enough in my original description. I think that all of the solutions (which are great and provided me with information that will come in handy in the near future) are totaling the sum's of the values in the drop downs. Which reading back is what it sounds like I was attempting. However there is more that I am looking to do.
What I want to happen is the user (ME) Will select the variables with the drop downs. i.e. 4 die rolls of 8 sided dice with a + 4 modifier. All of the solutions appear to be taking the values (4, 8, 4) and adding them for a total of 16 when I am trying to get the total of 4 eight sided dice + 4. which should return a value between 8 (1,1,1,1,4) and 36 (8,8,8,8,4). I hope that clears it up.
This might help as well, Currently this is part of another script.
function getRandom() {
return Math.floor(Math.random() * 6) + 1;
for this function I would want the drop down for sidePerDie to change the multiplier to the value of the drop down. Either 4, 6, 8, 10, 12 or 20.
and also the following
for(var i = 0; i < 4; ++i) {
roll = getRandom();
diceTotal += roll;
d.push(roll);
}
This rolls the dice 4 times. I would like the drop down to change the 4 to the number of rolls that i would like.
That way when I click the Get hit points button. the function will fire and roll the type of die (4, 6, 8, etc side) a number of times (1-10) and then add the modifier to the total.
var submit_button = document.getElementById("form_submit");
submit_button.addEventListener("click", getSum);
function getSum() {
var constMod = parseInt(document.getElementById("constMod").value),
sidesPerDice = parseInt(document.getElementById("sidesPerDice").value),
numberOfDice = parseInt(document.getElementById("numberOfDice").value);
var total=0;
var div_to_fill = document.getElementById("getHitPoints");
var randomVariableArray = getRandom(numberOfDice, sidesPerDice, constMod);
console.log(randomVariableArray);
for(var i in randomVariableArray) {
total += randomVariableArray[i];
}
div_to_fill.innerHTML = total;console.log(total);
}
function getRandom(numberOfDice, sidesPerDice, constMod) {
var arr = [];
for(var i = 0; i < numberOfDice; ++i) {
rollDie = Math.floor(Math.random() * sidesPerDice) + 1;
arr.push(rollDie);
}
arr.push(constMod);
return arr;
}
<html>
<head></head>
<body>
<form id="totalHitPoints">
<div class="w3-container w3-center w3-blue">
<h1>Monster Stat Generater</h1>
</div>
<div class="w3-container">
<p>Number of Dice:</p>
<select id="numberOfDice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="w3-container">
<p>Number of Sides per Dice</p>
<select id="sidesPerDice">
<option value="4">4 sides</option>
<option value="6">6 sides</option>
<option value="8">8 sides</option>
<option value="10">10 sides</option>
<option value="12">12 sides</option>
<option value="20">20 sides</option>
</select>
</div>
<div class="w3-container">
<p>Constitution Modifier</p>
<select id="constMod">
<option value="0">0plus</option>
<option value="1">1plus</option>
<option value="2">2plus</option>
<option value="3">3plus</option>
<option value="4">4plus</option>
<option value="5">5plus</option>
<option value="6">6plus</option>
<option value="7">7plus</option>
<option value="8">8plus</option>
<option value="9">9plus</option>
<option value="10">10plus</option>
</select>
</div>
<br>
</form>
<button id="form_submit" type="submit">Get Hit Points</button>
<div class="w3-container" style="width:128px;">
<p>Total Hit Points:</p>
<p id="getHitPoints"class="w3-border w3-center w3-padding" style="width: 64px;">0</p>
</div>
</body>
</html>
EXPLANATION: first of all your option values should be integers and unqiue.. make your html as follows:
<form id="totalHitPoints">
<div class="w3-container w3-center w3-blue">
<h1>Monster Stat Generater</h1>
</div>
<div class="w3-container">
<p>Number of Dice:</p>
<select id="numberOfDice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div class="w3-container">
<p>Number of Sides per Dice</p>
<select id="sidesPerDice">
<option value="4">4 sides</option>
<option value="6">6 sides</option>
<option value="8">8 sides</option>
<option value="10">10 sides</option>
<option value="12">12 sides</option>
<option value="20">20 sides</option>
</select>
</div>
<div class="w3-container">
<p>Constitution Modifier</p>
<select id="constMod">
<option value="0">0plus</option>
<option value="1">1plus</option>
<option value="2">2plus</option>
<option value="3">3plus</option>
<option value="4">4plus</option>
<option value="5">5plus</option>
<option value="6">6plus</option>
<option value="7">7plus</option>
<option value="8">8plus</option>
<option value="9">9plus</option>
<option value="10">10plus</option>
</select>
</div>
<br>
</form>
<button id="form_submit" type="submit">Get Hit Points</button>
<div class="w3-container" style="width:128px;">
<p>Total Hit Points:</p>
<p id="getHitPoints"class="w3-border w3-center w3-padding" style="width: 64px;">0</p>
</div>
next your javascript function add a event listener click:
var submit_button = document.getElementById("form_submit");
submit_button.addEventListener("click", getSum);
then define the actual function which calculates sum.
Then first parse the options to int:
function getSum() {
var constMod = parseInt(document.getElementById("constMod").value),
sidesPerDice = parseInt(document.getElementById("sidesPerDice").value),
numberOfDice = parseInt(document.getElementById("numberOfDice").value);
Then dine another function getRandom which gets the number of random dies as array
var randomVariableArray = getRandom(numberOfDice, sidesPerDice, constMod);
function getRandom(numberOfDice, sidesPerDice, constMod) {
var arr = [];
for(var i = 0; i < numberOfDice; ++i) {
rollDie = Math.floor(Math.random() * sidesPerDice) + 1;
arr.push(rollDie);
}
arr.push(constMod);
return arr;
}
Then loop through the array and add all the values
for(var i in randomVariableArray) {
total += randomVariableArray[i];
}
the fill the div with the sum using innerHtml
var div_to_fill = document.getElementById("getHitPoints");
div_to_fill.innerHTML = total;console.log(total);
}
on whole you js will be
var submit_button = document.getElementById("form_submit");
submit_button.addEventListener("click", getSum);
function getSum() {
var constMod = parseInt(document.getElementById("constMod").value),
sidesPerDice = parseInt(document.getElementById("sidesPerDice").value),
numberOfDice = parseInt(document.getElementById("numberOfDice").value);
var total=0;
var div_to_fill = document.getElementById("getHitPoints");
var randomVariableArray = getRandom(numberOfDice, sidesPerDice, constMod);
console.log(randomVariableArray);
for(var i in randomVariableArray) {
total += randomVariableArray[i];
}
div_to_fill.innerHTML = total;console.log(total);
}
function getRandom(numberOfDice, sidesPerDice, constMod) {
var arr = [];
for(var i = 0; i < numberOfDice; ++i) {
rollDie = Math.floor(Math.random() * sidesPerDice) + 1;
arr.push(rollDie);
}
arr.push(constMod);
return arr;
}
Link to fiddle: [https://jsfiddle.net/qfxvydmp/][1]
This is indeed possible. This post on eduMaven does a good job of showing how to do pretty much this exact thing: http://edumaven.com/javascript-programming/get-value-of-selected-option . This post gives an example in pure JS:
var selector = document.getElementById('id_of_select');
var value = selector[selector.selectedIndex].value;
This is easy enough to do is pure JS, but another search for the same problem in jQuery pulls up this example: https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/ . This post shows that the jQuery way is just:
var value = $( "#myselect" ).val();
It is a little bit unclear exactly what you want to do with this information. I am assuming based on what you did say that you want to do something with the selected values when the user clicks "submit", without actually sending an HTTP request.
To do this part, I would actually skip the "submit" type of the button, and instead define an "onclick" event for the button, as shown here: http://www.w3schools.com/jsref/event_onclick.asp . The example given is:
<button onclick="myFunction()">Click me</button>
Then, you will need to define a function in your JS file to actually perform whatever computation you want to do. This could really be any calculation you want--this is just a matter of manipulating javascript variables. From what you say you want above, it would look something like:
function myFunction(){
// get the integer values from your select options
var numDice = parseInt( $( "#numberOfDice" ).val() );
var sidesDice = parseInt( $( "#sidesPerDice" ).val() );
var mod = parseInt( $( "#constMod" ).val() );
// "roll" numDice times
var sum = 0;
for (i = 0; i < numDice; i++) {
// roll a random number and add mod, then add to sum
sum += Math.floor((Math.random() * sidesDice) + 1) + mod;
}
// output answer in whatever form you see fit --
// could be put back into the html (as shown in the links provided), printed to console, or used in a later calculation
console.log(sum);
}
I hope this walkthrough will help point you and others in the right direction with some of this stuff. However, you should really look into some of the basics of using jQuery of JS to select html elements--this really is pretty much the basic use case of these technologies! It would be helpful for you to get more familiar with the basics before trying to fell your way blindly here. There are plenty of resources online, including the ones I linked to (which were found by a quick search; that said, knowing the proper search terms can, admittedly, be tricky).
First of all - remove the value attribute from each option element as this will make things easier when obtaining the values from the select elements
<div class="w3-container">
<select id="numberOfDice">
<option>1</option>
<option>2</option>
<option>3</option>
....
</select>
</div>
<div class="w3-container">
<p>Number of Sides per Dice</p>
<select id="sidesPerDice">
<option>4</option>
<option>6</option>
<option>8</option>
...
</select>
</div>
<div class="w3-container">
<p>Constitution Modifier</p>
<select id="constMod">
<option>0</option>
<option>1</option>
<option>2</option>
...
</select>
</div>
You can remove the form element also.
You need to add a JavaSCript event to the button so it knows what to do once you click on the button.
<button id="form_submit" onclick='doCalc()'>Get Hit Points</button>
You need a JavaScript function
function doCalc() {
//--- get the input values
var parseInt(numberOfDice = document.getElementById('numberOfDice').value,10);
...
//-- do you calculations
...
//--- display your results
document.getElementById('getHitPoints').innerHTML = myResults;
}
The values for your select dropdowns don't have to be unique, they can be anything you like. You've given each of your selects a unique id e.g id="numberOfDice" which is good - the <option> tag in each of them is a child of the <select> tag, and we can get that value using javascript.
I'd remove the text from your values so you're just dealing with numbers - e.g value="plus0" should become value="0" for everything.
Include the jquery library in your head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
Then in your Script.js add the following
$( document ).ready(function() {
// listen for a click event on your button
$('#form_submit').click(function(event) {
// stop the form submitting data - we just want to update your html
event.preventDefault();
// get the values of your selects as variables
var numberOfDice = $('#numberOfDice').val();
var sidesPerDice = $('#sidesPerDice').val();
var constMod = $('#constMod').val();
// do the calculation
var sum = numberOfDice + sidesPerDice + constMod;
// now update your html with your calculation
$('p#getHitPoints').html(sum);
});
});

How do I have my drop down selections submit in the HTML form?

I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.

Categories

Resources