JS script - Value Dependent (multiple dropdown) - javascript

Right now I have two dropdowns and the goal is to have the User select "OFF" on the first option, the second dropdown automatically selects "ON" and vice versa.
The code currently below with the JavaScript works, but works for only one pair of the dropdown. I was wondering what I need to change to make it work for both pairs or even four pairs in the future.
Code:
<!DOCTYPE html>
<html>
<body>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
<option value="">Select Option</option>
<option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
<option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class="microphone select2" name = "microphone">
<option value=" " selected="selected">Select Option</option>
<option value="ON. Thank you.">ON</option>
<option value="OFF. Thank you.">OFF</option>
</select>
</div>
<br>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
<option value="">Select Option</option>
<option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
<option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class="microphone select2" name = "microphone">
<option value=" " selected="selected">Select Option</option>
<option value="ON. Thank you.">ON</option>
<option value="OFF. Thank you.">OFF</option>
</select>
</div>
</form>
</div>
<script>
const cmicrophone = document.querySelectorAll('.select1')[0];
const microphone = document.querySelectorAll('.select2')[0];
function inputHandler(thisSelect, otherSelect) {
otherSelect.selectedIndex =thisSelect.selectedIndex
}
cmicrophone.addEventListener('change', event => {
inputHandler(cmicrophone, microphone);
});
microphone.addEventListener('change', event => {
inputHandler(microphone, cmicrophone);
});
</script>
</body>
</html>

Here is your solution
<!DOCTYPE html>
<html>
<body>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
<option value="">Select Option</option>
<option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
<option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class="microphone select2" name = "microphone">
<option value=" " selected="selected">Select Option</option>
<option value="ON. Thank you.">ON</option>
<option value="OFF. Thank you.">OFF</option>
</select>
</div>
<br>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
<option value="">Select Option</option>
<option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
<option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class="microphone select2" name = "microphone">
<option value=" " selected="selected">Select Option</option>
<option value="ON. Thank you.">ON</option>
<option value="OFF. Thank you.">OFF</option>
</select>
</div>
</form>
</div>
<script>
var cmicrophone = document.querySelectorAll('.select1');
var microphone = document.querySelectorAll('.select2');
function inputHandlerCmicrophone(thisSelect, otherSelect, j) {
var test = document.querySelectorAll('.select1');
for(i=0; i<test.length; i++){
if(test[i] == j){
otherSelect[i].selectedIndex =thisSelect[i].selectedIndex
break;
}
}
}
function inputHandlerMicrophone(thisSelect, otherSelect, j) {
var test = document.querySelectorAll('.select2');
for(i=0; i<test.length; i++){
if(test[i] == j){
otherSelect[i].selectedIndex =thisSelect[i].selectedIndex
break;
}
}}
for(i=0; i<cmicrophone.length; i++) {
cmicrophone[i].addEventListener('change', function (e) {
inputHandlerCmicrophone(cmicrophone, microphone, e.target);
});
}
for(k=0; k<microphone.length; k++) {
microphone[k].addEventListener('change', function (e) {
inputHandlerMicrophone(microphone, cmicrophone, e.target);
});
}
</script>
</body>
</html>

I would suggest using document.getElementById() instead of querySelectorAll(). The problem is that you're always accessing the first one, element 0. You also need to ensure you have unique values for each 'id' property; in the code above you have duplicate values for microphone and cmicrophone.
You will need to add a loop for dynamic number of selects by fetching all of them and iterating over them to map each of the event handlers:
const cmicrophones = document.querySelectorAll('.select1');
const microphones = document.querySelectorAll('.select2');
for (var i = 0; i < cmicrophones.length; i++) {
const cmicrophone = cmicrophones[i];
const microphone = microphones[i];
....
}

Related

How to get multiple values from an HTML <select> element

How to take the values of value1 and value2 in two variables using javascript?
<select class="form-control" id="country" name="country">
<option value="**value1**" "**value2**" >Select Item</option>
</select>
You could make your own attribute. I know you probably do not want to get the element with an ID, but I don't know the context. You can just call getAttribute on the option and use any name you gave to the "custom" attribute.
window.addEventListener('load', ()=>
{
const option = document.getElementById('option');
function init()
{
//Use this to get the values
console.log(option.getAttribute('other-value'));
}
init();
});
<select class="form-control" id="country" name="country">
<option id="option" value="value1" other-value="value2">Select Item</option>
</select>
I don't know what you really want to do with your piece of code,
but here is a proper way to use the option elements, and a way to split multiple values with a fixed separator:
var example = document.getElementById('example');
example.addEventListener('change', function() {
// Console displays the “value”, and not the text, of the selected option
console.log("option value:", example.value);
});
// Here is what I'll do with your "multiple" values
var country = document.getElementById('country');
var options = country.querySelector('option');
var values = options.value.split("/");
values.forEach(function(val) {
country.innerHTML += "<option value=" + val + ">" + val + "</option>";
});
<p>My simple example</p>
<select id="example" name="country">
<option value="--">Select Country</option>
<option value="GB">Great Britain</option>
<option value="FR">France</option>
</select>
<br>
<br>
<p>Example with option getting splitted</p>
<select class="form-control" id="country" name="country">
<!-- Let's say your multiple values are separated by a "/" -->
<option value="**value1**/**value2**">Select Item</option>
</select>
Hope it helps.
$('select').on('change', function() {
console.log( $('#country').val() );
console.log($(this).find(':selected').data('second'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="country" name="country">
<option value="value1" data-second ="value2" >Select Item 1</option>
<option value="value3" data-second ="value4" >Select Item 2</option>
</select>

Javascript change input value when select option is selected

I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:
First Name: <input type="text" value="colors">
<select name="">
<option>Choose Database Type</option>
<option onclick="myFunction(g)>green</option>
<option onclick="myFunction(r)>red</option>
<option onclick="myFunction(o)>orange</option>
<option onclick="myFunction(b)>black</option>
</select>
<script>
function myFunction(g) {
document.getElementById("myText").value = "green";
}
function myFunction(r) {
document.getElementById("myText").value = "red";
}
function myFunction(o) {
document.getElementById("myText").value = "orange";
}
function myFunction(b) {
document.getElementById("myText").value = "black";
}
</script>
A few things:
You should use the onchange function, rather than onclick on each individual option.
Use a value attribute on each option to store the data, and use an instance of this to assign the change (or event.target)
You have no ID on your text field
You're missing the end quote for your onclick function
<select name="" onchange="myFunction(event)">
<option disabled selected>Choose Database Type</option>
<option value="Green">green</option>
<option value="Red">red</option>
<option value="Orange">orange</option>
<option value="Black">black</option>
</select>
And the function:
function myFunction(e) {
document.getElementById("myText").value = e.target.value
}
And add the ID
<input id="myText" type="text" value="colors">
Fiddle: https://jsfiddle.net/gasjv4hs/
More proper way is to put your JS code in a different .js file and use Jquery as when you go further with your programming this is the proper way.
Your HTML
<input type="text" id="color" name="color">
<select name="" id="changeData">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
Your JS
$(document).ready(function () {
$('#changeData').change(function(){
var color = $(this).val();
$('#color').val(color);
})
});
Also make sure that you have added Jquery Library to your Project. You can either download Jquery and add in your project folder OR also you can use CDN. in this example CDN is used.
I came up with a similar problem. In my case i was trying to change the minimum value of an input based on the value of an option in a select list. I tried to apply the above solutions but nothing worked. So i came with this, which can be applied to problems similar to this
HTML
<input id="colors" type="text" value="">
<select id="select-colors" name="" onchange="myFunction()">
<option disabled selected>Choose Colour</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="orange">orange</option>
<option value="black">black</option>
</select>
JS
function myFunction() {
var x = document.getElementById("select-colors").value;
document.getElementById("colors").value = x;
}
This works by getting the value of the select with id "select-colors" on every change, assigning it into a variable "x" and inserting it into the input value with id "colors". This can be implemented in anyway based on your problem
You create functions with same name multiple times.
Only last one will work.
the variables you pass g,r,o,b are undefined.
Don't add onclick to option add onchange to select.
Make use of HTML5 data-* attribute
function myFunction(element) {
document.getElementById("myText").value = element;
}
First Name: <input type="text" id="myText" value="colors">
<select name="" onchange="myFunction(this.value);">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
You can resolve it this way.
` First Name:
<select name="" onchange="myFunction()" id="selectID">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script>
function myFunction() {
var selectItem = document.getElementByID('selectID').value;
document.getElementByID('yourId').value = sekectItem;
}
</script>
Here's a way to achieve that:
var select = document.getElementById('colorName');
function myFunction(event) {
var color = 'No color selected';
if (select.selectedIndex > 0) {
color = select.item(select.selectedIndex).textContent;
}
document.getElementById('myText').value = color;
}
select.addEventListener('click', myFunction);
myFunction();
First Name: <input type="text" id="myText">
<select id="colorName">
<option>Choose Database Type</option>
<option>green</option>
<option>red</option>
<option>orange</option>
<option>black</option>
</select>
Your code should be like following.
<input type="text" name="color" id="color">
<select name="" id="change_color">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function () {
$('#change_color').change(function(){
var color = ($(this).val());
$('#color').val(color);
})
});
</script>
Here is JS Code that worked for me
var selectYear = document.getElementById('select-year');
selectYear.addEventListener('change', function() {
var selectedYear = document.getElementById('selected-year');
selectedYear.innerHTML = selectYear.value;
});
Select Input ID: select-year
Text ID: selected-year
Code generated from Codex AI :)

Showing select options on different select options

I want when someone selects a country out of my list the province in that country show up in the second select bar is this possible within html? And if not how do I do it with javascript.
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select> OPTIONS FOR HOLLAND
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select> OPTIONS FOR ENGLAND ETC...
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
</body>
</html>
You'll probably have to do this using JavaScript. I've edited your HTML a bit to make the selection process easier. There might be a way with HTML form elements, but try this:
var countrySelect = document.getElementById('countries'); //the main select
var countryClass = document.getElementsByClassName('country'); //the other selects
countrySelect.onchange = function(){
var selected = this.children[this.selectedIndex].value; //this is the value of the country select;
for(var i = 0; i < countryClass.length; i++)
countryClass[i].style.display = countryClass[i].id === selected ? 'block' : 'none';
}
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countries">
<option disabled selected>Select Country</option>
<option value="Holland">Holland</option>
<option value="Denmark">Denmark</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
</select><br>
Provincie:
<select class="country" id="Holland" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select class="country" id="England" style="display:none;">
<option disabled selected>Select Location</option>
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
</body>
I am not sure about the html way but the jquery way is pretty easy.
Handle option selected of countries. Based on the country selected hide/show provinces:
$(document).ready(function(){
$('#countries').on('change',function(){
var selectedCountry = $(this).find('option:selected').text();
switch (selectedCountry){
case 'Holland':
// hide show provice
break;
//etc
}
});
});
You need to use JS and play with elements display property.
After user selects a country hide province select (code snippet below hides all selects sharing toggle class), then identify which country was selected and show the province select for that country. Voilà!
<!DOCTYPE html>
<html>
<head>
<title>Gegevens</title>
</head>
<body>
<center>
<h1>Gegevens</h1>
</center>
Land:
<select id="countrySelect" onchange="toggleCountry()">
<option value="Holland">Holland</option>
<option value="England">England</option>
</select><br>
Provincie:
<select id="provinceHolland" class="toggle">
<option value="Gelderland">Gelderland</option>
<option value="Utrecht">Utrecht</option>
</select>
<select id="provinceEngland" class="toggle" style="display:none">
<option value="Schotland">Schotland</option>
<option value="Wales">Wales</option>
</select>
<footer>Ga terug</footer>
<script>
function toggleCountry() {
var list = document.getElementsByClassName("toggle");
for (var i = 0; i < list.length; i++) {
list[i].style.display = "none";
}
var sub = "province" + document.getElementById("countrySelect").value;
document.getElementById(sub).style.display = "inline";
}
</script>
</body>

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);
});
});

get selected option from document.getElementsByTagName("option")

I have html code this is a part of it :
<select id="year_marine_second_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="103">Lectures</option>
<option value="104">Courses</option>
<option value="105">Sheets</option>
<option value="106">Others</option>
</select>
<select id="year_marine_third_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="107">Lectures</option>
<option value="108">Courses</option>
<option value="109">Sheets</option>
<option value="110">Others</option>
</select>
<select id="year_marine_fourth_choose" style="display: none">
<option value="" style="display:none;"></option>
<option value="111">Lectures</option>
<option value="112">Courses</option>
<option value="113">Sheets</option>
<option value="114">Others</option>
</select>
this is the javascript code where the problem is :
var get_value = document.getElementsByTagName("option");
alert(get_value[5].value);
this code get the value of the 6th option .. any idea of how to get the value of the selected option by the user not the [5]
Javascript arrays start counting from 0, so [0] is the first element. Which means you maybe need alert(get_value[4].value);
In case you need the selected option you can use:
var all_select = document.getElementsByTagName("select");
for (i = 0; i < all_select.length; i++) {
all_select[i].onchange = function () {
alert(this.value);
}
}
Demo here

Categories

Resources