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>```
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}~;
}
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;
}
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);
});
});
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.