passing option value in html as javascript parameter - javascript

I made a simple html and javascript file to help me roll dice in DND. Currently this seems to be working fine
index.html
<form>
<input type="number" id="diceType"> dice type (d20, d12 ect ...)<br>
<input type="number" id="diceNumber"> number of dice<br>
<input type="number" id="mod"> mod<br>
</form>
<button type="button" onclick="roll(document.getElementById('diceType').value, document.getElementById('diceNumber').value, document.getElementById('mod').value)">
Roll
</button>
index.js
const roll = function(diceType, diceNumber, mod){
let total = 0;
let div1 = document.getElementById("rolling");
div1.innerHTML = '';
for(let i = 0; i < diceNumber; i++){
let roll = Math.floor(Math.random() * (diceType - 1 + 1) ) + 1;
total += roll;
div1.innerHTML += 'you rolled ' + roll + "<br>";
}
let result = parseInt(total) + parseInt(mod);
document.getElementById("youRolled").innerHTML =
'You rolled ' + diceNumber + 'D' + diceType + ' modifier was ' + mod + ' total: ' + result
};
However, I find this a little clunky as I want to have a selection drop down list, have the user select the option, then pass that as a parameter to the roll function.
I have tried using
<select>
<option value="100">D100</option>
<option value="20">D20</option>
<option value="12">D12</option>
<option value="10">D10</option>
<option value="8">D8</option>
<option value="6">D6</option>
<option value="4">D4</option>
</select>
I have tried a few things but I was wondering how would I access say
<option value="12">D12</option>
that value then pass it into
onclick="roll()"
as one of the parameters. That why I figure it would prevent me or others from selecting a million different dice combinations to enter. Also, I do know there is other generators out there, but was looking to try and make my own for fun.

Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Like this:
const fields = ['diceType', 'diceNumber', 'mod'].map(id => document.getElementById(id));
document.querySelector('button')
.addEventListener('click', () => roll(...fields.map(field => field.value)));
And for the roll function:
const roll = function(diceType, diceNumber, mod){
const selectedValue = document.querySelector('select').value;
let total = 0;
// ...
values are strings, so if needed, to turn selectedValue into a number, call Number on it while defining the variable:
const selectedValue = Number(document.querySelector('select').value);

In your code you have to add id to the <select> tag
If you have a select element that looks like this:
<select id="diceValue">
<option value="100">D100</option>
<option value="20">D20</option>
<option value="12">D12</option>
<option value="10">D10</option>
<option value="8">D8</option>
<option value="6">D6</option>
<option value="4">D4</option>
</select>
Running this code:
var e = document.getElementById("diceValue");
var value = e.options[e.selectedIndex].value;
Would make value to be option value. If what you actually want is D100, then do this:
var e = document.getElementById("diceValue");
var value = e.options[e.selectedIndex].text;
Which would make value be D100.
To pass the value inside the function just use :
onClick = roll(document.getElementById('diceValue').value ,..other arguments)

Related

Getting `<option>` value from `<select>` using JavaScript only works in debug mode

I am working on this project where I need to get the selected value from the user and and do a simple if - else. However, I'm not being able to get the value of the selected option from the user.
<select id = "insulinStrength" name="insulinStrength" type="text" class="selectBtn" >
<option value="">Select Insulin Type</option>
<option value="Novolog">Novolog</option>
<option value="Humalog">Humalog</option>
<option value="Apidra">Apidra</option>
<option value="Velosulin">Velosulin</option>
</select>
function getInsulinStrength() {
let insulinSt = document.getElementById('insulinStrength'),
selectedNode = insulinSt.options[insulinSt.selectedIndex];
if (selectedNode.value ==="Humalog"){
insulinStrengthTotal = 1800;
} else {
insulinStrengthTotal = 1500;
}
return insulinStrengthTotal;
}
This value needs to be put in the function below:
function doTheMath(){
let carbIntake = getCurrentMeal();
let cbs = getCurrentBloodSugar();
let tbs = getTargetBloodSugar();
let br = getBasalRate();
let is = getInsulinStrength();
let dailyBasalRate = br * 24;
let gramsPerInsulin = 450 / dailyBasalRate;
let bolus = carbIntake / gramsPerInsulin;
if (cbs > tbs) {
let correctionFactor = is / dailyBasalRate;
let correctionDose = (cbs - tbs) / correctionFactor;
bolus += correctionDose;
}
return bolus;
}
Everything else works minus the getInsulinStrength() function. Regardless of what the user chooses, it returns the same value.
The result is supposed to change when the user chooses Humalog. But the results always stay the same for every single selected value.
IT HAS CORRECT FUNCTIONALITY ONLY IN DEBUG MODE, HOWEVER IN REGULAR BROWSER MODE IT DOESN'T.
I don't know how your code works or when you execute that function, but here you have a snippet that alerts when you select an option form the select.
https://jsfiddle.net/MSclavi/m641xba9/5/
Adding onchange to the select works like a charm
<select id = "insulinStrength" onchange="getInsulinStrength()" name="insulinStrength" class="selectBtn" >
<option value="">Select Insulin Type</option>
<option value="Novolog">Novolog</option>
<option value="Humalog">Humalog</option>
<option value="Apidra">Apidra</option>
<option value="Velosulin">Velosulin</option>
</select>
Maybe you can merge that with your code, but in following questions, please provide a fiddle or a working code. Cheers!

How to change to default the selected dropdown [duplicate]

I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P

How to find average of innerHTMLs?

I have input fields and selects. For different select options there are different equations. After calculating equations, I used .innerHTML to show results. I got first part of the code worked, but I am stuck at the last part. When I try to calculate average of outputs, It shows Nan. Can anyone help with this problem? Thanks in advance.
var container = document.getElementById('container');
var span1 = document.getElementById('span1');
var span2 = document.getElementById('span2');
var output = document.getElementById('output');
function average() {
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseFloat(document.getElementById('d').value);
if (document.getElementById('select1').value == '1') {
span1.innerHTML = ((a+b)/(a*b)).toFixed(2);
} else if (document.getElementById('select1').value == '2') {
span1.innerHTML = ((a*b)/(a+b)).toFixed(2)
} else {
span1.innerHTML = '';
}
if (isNaN(span1.innerHTML)) {
span1.innerHTML = '';
}
if (document.getElementById('select1').value == 'none1') {
span1.innerHTML = 'None'
}
if (document.getElementById('select2').value == '3') {
span2.innerHTML = ((c+d)*100/(c*d)).toFixed(2);
} else if (document.getElementById('select2').value == '4') {
span2.innerHTML = ((c*d)*100/(c+d)).toFixed(2)
} else {
span2.innerHTML = '';
}
if (isNaN(span2.innerHTML)) {
span2.innerHTML = '';
}
if (document.getElementById('select2').value == 'none2') {
span2.innerHTML = 'None'
}
var percent = document.getElementsByClassName('percent');
for (var i = 0; percent.length > i; i++) {
if (percent.length > 0) {
output.innerHTML = percent[i]/(percent.length);
}
}
}
container.addEventListener('change', average);
container.addEventListener('input', average);
<div id="container">
<input id="a" type="number">
<input id="b" type="number">
<select name="abc" id="select1">
<option value="Choose">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="none1">None</option>
</select>
<br>
<input id="c" type="number">
<input id="d" type="number">
<select name="abcd" id="select2">
<option value="Choose">Choose...</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="none2">None</option>
</select>
<span id="span1" class="percent"></span>
<span id="span2" class="percent"></span><br>
<span id="output"></span>
</div>
.innerHTML gets or sets the content of an element by invoking the HTML parser on the string passed as the value or extracted from the element. When the content is, or is to become just text (no HTML to be parsed), you should use .textContent as this will not invoke the HTML parser on the content, which saves processing power. In your case, you should be using .textContent.
Now, either way, data sent to or gotten from either .innerHTML or .textContent is a string, so if you want to do math with the value, you need to first convert it to a number. This can be done in several ways:
parseInt(stringToBeConverted, radix)
parseFloat(stringToBeConverted)
Number(stringToBeConverted)
+stringToBeConverted
Now, you have two issues, first when some of the text fields are still empty, their value is an empty string and parseFloat() on an empty string returns NaN. This can be solved by giving each field a default value of 0 in the HTML (i.e. <input id="a" type="number" value="0">).
Second, even with a, b, c, and d all having numeric values, your math:
((a + b) / (a * b)).toFixed(2);
Will result in NaN when a * b results in 0 because that will result in a division by zero situation.
You need to change your algorithm to test for this situation before doing the math.
I have no idea what you're trying to do, but I think this might be the correct solution it's a working way of getting the value of the percent[i] HTML element:
Change
output.innerHTML = percent[i]/(percent.length);
to
output.innerHTML = percent.item(i).innerHTML/(percent.length);
or
output.innerHTML = percent[i].innerHTML/(percent.length);

2 variables from select box and hidden input

How can I get 2 different variables from select box and hidden inputs in jquery, i.e:
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text1">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text2">
<br />
<select name="startID[]" class="startID">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" name="startText[]" value="Text3">
so I have 3 select boxes with 3 hidden inputs, how can I get the value of each select boxed and the text that is attached to? i.e: if I select like this:
Select item is 1 and text is Text1
Select item is 3 and text is Text2
Select item is 2 and text is Text3
Thanks in advance
function getValues() {
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
});
}
If you want to list the values on change:
$('select.startID,input[type="hidden"]').change(getValues);
Demo (modified a bit):
http://jsfiddle.net/6ev9evew/
NOTE
The updates below are not answers for the original question, but the question's author keeps posting extra questions in the comments! So the solution is above!
UPDATE:
As I can understand this is what you looking for:
function getValues() {
var me = this;
$('select').each(function (idx, el) {
console.log("Select item is " + $(el).val() + " and text is " + $(el).next('input[type="hidden"]').val());
if (el === me) return false;
});
}
So basically we stop the loop at the actual element. But it works only if you pass this function to an event handler.
DEMO 2: http://jsfiddle.net/6ev9evew/1/
UPDATE 2:
So, according to the third question, this is a version of the implementation. As I mentioned below in the comments section, there are multiple ways to implement it. This implementation uses that the array indexes are always in order.
function getValues() {
var result = [];
var me = this;
$('select').each(function (idx, el) {
var $el = $(el);
result[10*$el.val()+idx]=("Select item is " + $el.val() + " and text is " + $el.next('input[type="hidden"]').val()+'<br />');
if (me === el) return false;
});
$('#res').html(result.join(''));
}
$('select.startID,input[type="hidden"]').change(getValues);
DEMO 3:
http://jsfiddle.net/6ev9evew/2/
But you can also implement it with array.sort(fn) but than you do a second iteration on the result set.
Anyway if you have more than ten selects in your real code, don't forget to modify the multiplier at result[10*$el.val()+idx] !
If you want to know the value of the changed select (when the user selects a value on any of them) and also get the value of the input type hidden which is next to it, that's the way:
$('.startID').on('change', function () {
var sel = $(this).val();
var hid = $(this).next('input[type=hidden]').val();
console.log('Select item is ' + sel.toString() + ' and text is ' + hid.toString());
});
Demo
UPDATE
To achieve what you've asked in the comments, you can do it like this:
// Create two arrays to store the values.
var sel = [];
var hid = [];
$('.startID').on('change', function () {
// Put the selected values into the arrays.
sel.push($(this).val());
hid.push($(this).next('input[type=hidden]').val());
console.log(sel);
console.log(hid);
for (var i = 0; i < sel.length; i++) {
console.log('Select item is ' + sel[i].toString() + ' and text is ' + hid[i].toString());
}
});
Demo

Javascript - Getting dynamic name from HTML

I need to figure out how to make my javascript take in the select names dynamically. How should I go about this?
I've tried Tried var i = getElementsByName() and then if (i == "x) ... else .... with no results
My Javascript:
function displayResult()
{
var m=document.getElementsByName("x");
document.getElementById('divid').innerHTML = m[0].value;
}
My Html:
<form>
<select name = x>
<option> a </option>
<option> b </option>
<option> c </option>
</select>
<select name = y>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
</select>
</form>
The simplest solution would be with jQuery http://jquery.com
var myx = "x";
var elems = $("select[name=" + myx + "]");
Also with new browser APIs using pure Javascript:
var elems = document.querySelectorAll("select[name=x]")
https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
So you need that x to be 'dynamic'. I don't really understand what you mean with that but I guess you want to specify another name every time you call the function. That's what function parameters are for.
Change your function to this:
function displayResult(name)
{
var m=document.getElementsByName(name);
document.getElementById('divid').innerHTML = m[0].value;
}
Now you can call the function with:
displayResult("x");
I think that what you are actually looking for is this:
var nodes = document.getElementsByTagName('select');
var names = new Array();
for(i=0,c=nodes.length;i<c;i++){
names.push(nodes[i].name);
}
this code will produce an array names containing the names of selects presented on the page

Categories