Get Specific Index of Specific item from <select> to evaluate later - javascript

Okay to start of this is my main script that does the calculation for my specific problem, I don't understand why it doesn't output the correct result which is "Success" on the specified ID that I put it on. Is it something wrong with the index evaluations or I didn't properly get the index from my form.
function calculatePrice(){
var startLeague;
var targetLeague;
var startDiv;
var targetDiv;
var temp = document.getElementById("startLeague");
startLeague = temp.options[temp.selectedIndex].value;
startLeague = temp.indexOf(startLeague);
temp = document.getElementById("targetLeague");
targetLeague = temp.options[temp.selectedIndex].value;
targetLeague = temp.indexOf(targetLeague);
temp = document.getElementById("startDiv");
startDiv = temp.options[temp.selectedIndex].value;
startDiv = startDiv.indexOf(startDiv);
temp = document.getElementById("targetDiv");
targetDiv = temp.options[temp.selectedIndex].value;
targetDiv = temp.indexOf(targetDiv);
if(startLeague >= targetLeague){
document.getElementById("price-box").innerHTML = "Cannot Calculate";
//Ignore this line
setTimeout(initPrice, 5000);
}else{
if(startDiv >= targetDiv){
document.getElementById("price-box").innerHTML = "Cannot Calculate";
//Ignore this line
setTimeout(initPrice, 5000);
}else{
document.getElementById("price-box").innerHTML = "Success";
}
}
}
This is what I have for my HTML code and represents the values to be taken from the HTML itself via DOM.
<select id="startLeague">
<option value="Someval">0</option>
<option value="Someval1">1</option>
<option value="Someval2">2</option>
<option value="Someval3">3</option>
<option value="Someval4">4</option>
</select>
<select id="targetLeague">
<option value="Someval">0</option>
<option value="Someval1">1</option>
<option value="Someval2">2</option>
<option value="Someval3">3</option>
<option value="Someval4">4</option>
</select>
And so on...
This is my output paragraph that is used to check the value, so far when I click the button it doesn't do anything and remains blank, what is the problem?
<p id="price-box" style="margin: 0; padding: 0;"></p>
Clicking on the button as mentioned above doesn't do anything whereas it should be working.
<button type="button" onclick="calculatePrice()">Calculate</button>
As a final note, yes I have included the following line on the HTML head tag
<script src="price.js"></script>

Related

Selector Change based on previous selectors with dynamic lists

I am trying to generate a selector that populates with various tasks based on a previous selector. I have seen the short way to do it with if/else if block code, however for each of my selections I have 20+ options that could be chosen.
I have tried to put options on various sheets within the spread sheet and run a if/else if statement so the drop down will populate with tasks that are from one of the sheets associated with a selection option.
<!--my selection i want to base the next selection options off of-->
<select id = 'reason'>
<option value="" disabled selected>Choose Reason</option>
<option value = 'prec'>PREC</option>
<option value = 'crh'>CRH</option>
<option value = 'bh'>BH</option>
<option value = 'ih'>IH</option>
<option value = 'rh'>RH</option>
</select>
<Label>Call Reason</Label>
</div>
<!-- function that generates tasks dynamically from a sheet -->
function getTasks(){
var ss= SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName('PREC');
var list = ws.getRange(1,1).getDataRegion().getValues();
var options = {};
list.forEach(function(v){
options[v[0]]= null;
});
<!--essentially If someone chose "CRH" I would want it to open the sheet
with the CRH options -->
The way I wrote the loop didn't work.
function getTasks(){
var ss= SpreadsheetApp.openByUrl(url);
var options = {};
//basically added else ifs for each reason with the same code just dif
//sheet names
if (document.getElementById('reason')='prec'){
var ws = ss.getSheetByName('PREC');
var list = ws.getRange(1,1).getDataRegion().getValues();
list.forEach(function(v){
options[v[0]]= null;
}
});
return options
}
A Google Web App is in general composed of:
Apps Script code in the .gsfile
HTML code in the htmlfile
JavaScript code within the <script></script> tags
The interaction between those components:
In the .gs file a doGet()function must be implemented to create an HTML output
A JS function can be called from the htmlcode, e.g. <select id = 'reason' onchange="getSheet()">
An Apps Script function can be called from JS within the <script></script> part (alternatively within the <?...?> scriplets) with google.script.run, parameters can be passed to this function from the html file
A return value of a called Apps Script function can be passed back to JS with the withSuccessHandler
For your case:
The chosen dropdown option can accessed with JS (not with Apps Script!) part
var dropdown=document.getElementById('reason');
var sheet=dropdown.options[dropdown.selectedIndex].value;
The chosen sheet name needs to be passed to an Apps Script function where SpreadsheetApp methods are accessible
The options returned by the Apps Script function can be returned back to JS and implemented into the html framework
Here is how you can do it:
.gs file:
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function getTasks(sheet){
var ss= SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName(sheet);
var list = ws.getRange(1,1).getDataRegion().getValues();
var options = {};
list.forEach(function(v){
options[v[0]]= null;
});
return options;
}
html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<!--my selection i want to base the next selection options off of-->
<select id = 'reason' onchange="getSheet()">
<option value="" disabled selected>Choose Reason</option>
<option value = 'prec'>PREC</option>
<option value = 'crh'>CRH</option>
<option value = 'bh'>BH</option>
<option value = 'ih'>IH</option>
<option value = 'rh'>RH</option>
</select>
<Label>Call Reason</Label>
</div>
<script>
function getSheet(){
var dropdown=document.getElementById('reason');
var sheet=dropdown.options[dropdown.selectedIndex].value;
console.log(sheet);
google.script.run.withSuccessHandler(onSuccess).getTasks(sheet);
}
function onSuccess(options) {
//do something
}
</script>
</body>
</html>
I'm not sure if this is what you mean - why not use "onchange"?
<div>
<select id = 'reason1' onchange="MyFunction(0)">
<option value="" disabled selected>Choose Reason</option>
<option value = 'prec'>PREC</option>
<option value = 'crh'>CRH</option>
<option value = 'bh'>BH</option>
<option value = 'ih'>IH</option>
<option value = 'rh'>RH</option>
</select>
<Label>Call Reason</Label>
</div>
<div>
<div>
<select id = 'reason2' onchange="MyFunction(1)"><!--select[1]-->
<option value="" disabled selected>Choose Reason</option><!--opt[0]-->
<option value = 'prec2'>PREC</option><!--opt[1]-->
<option value = 'crh2'>CRH</option><!--opt[2]-->
<option value = 'bh2'>BH</option><!--opt[3]-->
<option value = 'ih2'>IH</option><!--opt[4]-->
<option value = 'rh2'>RH</option><!--opt[5]-->
</select>
<Label>Call Reason</Label>
</div>
<div>
<div>
<select id = 'reason3' onchange="MyFunction(2)"><!--select[3]-->
<option value="" disabled selected>Choose Reason</option>
<option value = 'prec3'>PREC</option>
<option value = 'crh3'>CRH</option>
<option value = 'bh3'>BH</option>
</select>
<Label>Call Reason</Label>
</div>
<div>
<script>
function MyFunction(x) {
//x - position of select in the array
var selects = [document.getElementById('reason1'), document.getElementById('reason2'), document.getElementById('reason3')]; //store all your selects in an array to easily get them
var url = 'your url here';
var selectedOption = selects[x].selectedIndex; //index of selected option
var selectedSelectId = event.target.id; //id of select changed
var ss = SpreadsheetApp.openByUrl(url);
var wsName = selectedSelectId + '-' + selectedOption;
var ws = ss.getSheetByName(wsName); //now you should name each of your spreedsheed "id of the select - option index", for example "reason1-1" for "prec", "reason3-2" for "crh3" etc;
//rest of your code here
}
</script>

How to refresh a value based on a drop down selection code igniter

I'm making a chart based on a drop down selection in code igniter, but I'm getting problems with refreshing the value after I select a drop down list.
I'm using onchange but it seems not to be working.
<form>
<select class="form-control btn-primary" id="sel1" onchange="window.setTimeout(function(){ document.location.reload(true); }, this.options[this.selectedIndex].value);">
<option value = "1">Layanan</option>
<option value = "2">Hasil</option>
<option value = "3">Waktu</option>
<option value = "4">Biaya</option>
</select>
</form>
var temp = document.getElementById("sel1").value;
The refresh page is working, but the value is not changing. It keeps getting back to the first selection. Any ideas?
As a solution (may not suit for your case): You need to pass parameter query along with window location string, but you should set an event listener for window load event:
HTML:
<select class="form-control btn-primary" id="sel1" onchange="reloader();">
<option value = "1">Layanan</option>
<option value = "2">Hasil</option>
<option value = "3">Waktu</option>
<option value = "4">Biaya</option>
</select>
Javascript:
function reloader(){
var param = document.getElementById('sel1').value;
var ref = window.location.href.split('?')[0];
if (param)
window.location.href = ref + "?sel1="+param;
}
window.addEventListener('load', function() {
var query = window.location.href.split('?')[1];
if (query) {
var qval = query.split('=')[1];
document.getElementById('sel1').value = qval;
} else {
document.getElementById('sel1').value = 1;
}
});
Try to use the https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Property/selectedIndex
It will help you select the desired option.
Something like this
document.getElementById("sel1").selectedIndex = 2;

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

Execution of Javascript not working on CodePen

I have been playing around with codepen.io and came across this particular issue for which I am not able to resolve.
My following pen does not work in codepen but works locally on my machine, I am not sure if I have to do something extra or enable a feature on codepen to make it work.
Any help most appreciated :)
HTML
<span>Background color:</span>
<select id="background">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<span>Width:</span>
<select id="width">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
</select>
<span>height:</span>
<select id="height">
<option value="100px">100px</option>
<option value="200px">200px</option>
<option value="300px">300px</option>
</select>
<br/>
<br/>
<div id="content" style="background:red; width:100px; height:100px;"></div>
JS
// array of virtual DOM objects
var arraySelect = document.getElementsByTagName('select');
var content = document.getElementById('content');
// function
function dropdownStyles() {
// apply the value from the select options (when applied) has the style values for content.
var style = this.id;
var value = this.value;
content.style[style] = value;
}
// create a loop to iterate each select option in document add an event listener to each.
for( var i = 0; i < arraySelect.lenght; i++ ){
// with dropdownStyles() the function will get executed so that is why we don't add the brackets
arraySelect[i].addEventListener('change',dropdownStyles);
}
Red box changer - codepen
Here is the working code.
var arraySelect = document.querySelectorAll('select');
var content = document.getElementById('content');
arraySelect.forEach(function(v){
v.addEventListener('change',dropdownStyles);
})
function dropdownStyles() {
var style = this.id;
var value = this.value;
content.style[style] = value;
}
this code will solve your problem.
There is a typo:
it's length not lenght
for( var i = 0; i < arraySelect.lenght; i++ ){
i < arraySelect.lenght
There is lenght ,not length.

Categories