Unable to fetch user input from drop-down list - javascript

I've been trying to fetch user input from a simple drop-down list to fill it into a <p> tag but can't seem to get it done.
The following is my javascript:
<script>
function changeText() {
var textDDL = document.getElementById("DDL1");
var text = textDDL.options[textDDL.selectedIndex].value;
var test = document.getElementById("test");
test.innerHTML = text;
}
</script>
The following is my HTML code:
<p class="first">
<label for="first">From</label>
<input list="countriesDL" name="country" class="form-control" type="text" id="DDL1">
<datalist id="countriesDL">
<option value="Afghanistan" class="form-control"></option>
<option value="Albania"></option>
<option value="Algeria"></option>
<option value="Aland Islands"></option>
<option value="American Samoa"></option>
<option value="Anguilla"></option>
<option value="Andorra"></option>
<option value="Angola"></option>
<option value="Antilles - Netherlands"></option>
<option value="Antigua and Barbuda"></option>
<option value="Antarctica"></option>
<option value="Argentina"></option>
<option value="Armenia"></option>
<option value="Australia"></option>
<option value="Taiwan"></option>
</datalist>
</p>
<button id="info2Btn" type="button" class="btn btn-warning leggo" style="color:black;" onClick="changeText()">Let's Go</button>
The codes would be triggered by a button press. I've tried reloading the page upon button press to see if it applies the user input, I've tried calling the function upon clicking the button. Can't seem to see what's wrong with it.

[UPDATED] Is this what you are trying?
function changeText() {
var textDDL = document.getElementById("DDL1");
var text = textDDL.value;
var test = document.getElementById("text");
test.innerHTML = text;
}
<p class="first">
<label for="first">From</label>
<input list="countriesDL" name="country" class="form-control" type="text" id="DDL1">
<datalist id="countriesDL">
<option value="Afghanistan" class="form-control"></option>
<option value="Albania"></option>
<option value="Algeria"></option>
<option value="Aland Islands"></option>
<option value="American Samoa"></option>
<option value="Anguilla"></option>
<option value="Andorra"></option>
<option value="Angola"></option>
<option value="Antilles - Netherlands"></option>
<option value="Antigua and Barbuda"></option>
<option value="Antarctica"></option>
<option value="Argentina"></option>
<option value="Armenia"></option>
<option value="Australia"></option>
<option value="Taiwan"></option>
</datalist>
</p>
<button id="info2Btn" type="button" class="btn btn-warning leggo" style="color:black;" onClick="changeText()">Let's Go</button>
<p id="text"></p>

Try
function changeText() {
document.getElementById("test").innerHTML = document.getElementById("DDL1").value;
}

Related

Multiplying select options by text-box user inputs in JavaScript

I am trying to create a simple website that calculates weight-based doses for pediatric medications. This is done by multiplying the dose per kilogram of a user-selected medication from a drop-down box by the user input of a text box. There is a second drop-down that contains the kilogram or pound options. kilogram value would be 1 and pound would be 2.2. So these three values together would be multiplied and the total would append to a readonly text box. I have been studying JS for weeks and still struggling with the most basic of projects. Any guidance would be appreciated.
HTML:
<div id="medications">
<select for="dropdown" id="medication">Select Medication
<option value="NaN">Select Medication</option>
<option value=".2">Adenosine .2mg/kg</option>
<option value=".15">Albuterol .15mg/kg</option>
<option value="5">Aminophylline 5mg/kg</option>
<option value="5">Amiodarone 5mg/kg</option>
<option value="5">Aspirin 5mg/kg</option>
<option value=".1">Ativan .1mg/kg</option>
<option value=".02">Atropine .02mg/kg</option>
<option value=".5">Atrovent .5mg/kg</option>
<option value="1">Benadryl 1mg/kg</option>
<option value=".01">Brethine .01mg/kg</option>
<option value="4">Dextrose 10% 4ml/kg</option>
<option value=".01">Epinephrine 1/10 .01mg/kg</option>
<option value=".01">Epinephrine 1/1 .01mg/kg</option>
<option value="1">Fentanyl 1mcg/kg</option>
<option value="1">Ketamine 1mg/kg</option>
<option value="1">Labetalol 1mg/kg/hr</option>
<option value="2">Levophed 2mcg/kg/min</option>
<option value="1">Lidocaine 1mg/kg</option>
<option value="50">Magnesium Sulfate 50mg/kg</option>
<option value=".1">Morphine .1mg/kg</option>
<option value="2">Narcan 2mg</option>
<option value=".25">Pepcid .25mg/kg</option>
<option value="1">Rocuronium 1mg/kg</option>
<option value="1">Sodium Bicarb 1mEq/kg</option>
<option value="1">Solu-Medrol 1mg/kg</option>
<option value=".5">Toradol .5mg/kg</option>
<option value=".1">Versed .1mg/kg</option>
<option value=".15">Zofran .15mg/kg</option>
</select>
</div>
<div id="weight">
<input id="number" type="text" placeholder="Weight" min="1" max="100">
<select for="dropdown" id="weightType">
<option value="1">Kg</option>
<option value="2.2">Lb</option>
</select>
</div>
<div id="totalDose">
<input id="dose" name="dose" type="text" READONLY placeholder="Dose">
</div>
There needs to be a point in time where the calculation should happen. That point in time corresponds to some action that the user will take and will be in the form of an "event".
Below, I've added a button for the user to "click" (which will be the event) that triggers the calculation.
See the inline comments for more details.
// Get reference to the output area (no need to input element - just populate the div) and the other elements
const output = document.querySelector("#totalDose");
const med = document.querySelector("#med");
const weight = document.querySelector("#weight");
const btn = document.querySelector("button");
// Set up a "click" event handler for the button
btn.addEventListener("click", function(event){
// Set the output element to the result of the math:
output.textContent = med.value * weight.value;
});
.title { display: inline-block; width: 150px; }
<div>
<span class="title">Select Medication:</span>
<select id="med">
<option value="NaN">Select Medication</option>
<option value=".2">Adenosine .2mg/kg</option>
<option value=".15">Albuterol .15mg/kg</option>
<option value="5">Aminophylline 5mg/kg</option>
<option value="5">Amiodarone 5mg/kg</option>
<option value="5">Aspirin 5mg/kg</option>
<option value=".1">Ativan .1mg/kg</option>
<option value=".02">Atropine .02mg/kg</option>
<option value=".5">Atrovent .5mg/kg</option>
<option value="1">Benadryl 1mg/kg</option>
<option value=".01">Brethine .01mg/kg</option>
<option value="4">Dextrose 10% 4ml/kg</option>
<option value=".01">Epinephrine 1/10 .01mg/kg</option>
<option value=".01">Epinephrine 1/1 .01mg/kg</option>
<option value="1">Fentanyl 1mcg/kg</option>
<option value="1">Ketamine 1mg/kg</option>
<option value="1">Labetalol 1mg/kg/hr</option>
<option value="2">Levophed 2mcg/kg/min</option>
<option value="1">Lidocaine 1mg/kg</option>
<option value="50">Magnesium Sulfate 50mg/kg</option>
<option value=".1">Morphine .1mg/kg</option>
<option value="2">Narcan 2mg</option>
<option value=".25">Pepcid .25mg/kg</option>
<option value="1">Rocuronium 1mg/kg</option>
<option value="1">Sodium Bicarb 1mEq/kg</option>
<option value="1">Solu-Medrol 1mg/kg</option>
<option value=".5">Toradol .5mg/kg</option>
<option value=".1">Versed .1mg/kg</option>
<option value=".15">Zofran .15mg/kg</option>
</select>
</div>
<div>
<span class="title">Select weight:</span>
<input id="number" type="text" placeholder="Weight" min="1" max="100">
<select id="weight">
<option value="1">Kg</option>
<option value="2.2">Lb</option>
</select>
</div>
<button type="button">Calculate</button>
<div id="totalDose"></div>

Adding and/or removing entire drop down select list

I want when a user clicks a button to be able to add or remove a drop down list for language select and proficiency. What js. code will work for me?
I have tried a couple of different codes from different sources but to no avail!
function addLanguage() {
var x = document.getElementById("dynamic-select");
x.labels[x.labels.length] = new Label('-- Choose a Language --', '0', false, false);
}
function removeLanguage() {
var x = document.getElementById("dynamic-select");
x.labels[x.labels.length - 1] = null;
}
function removeAllAddedLanguages() {
var x = document.getElementById("dynamic-select");
x.labels.length = 0;
}
<div id="dynamic-select">
<label for="dynamicSelect">
<select data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
<label for="proficiency">Level of proficiency</label>
<select name="pLevel" id="pLevel">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
<button onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>
I'm not sure if you want to do this, but this adds a new selectlist with profession, however I didn't handeld the names of the selectlists, so you may need to add it if you want to post via form.
function addLanguage() {
var langContainer = document.getElementById('dynamic-select');
var firstLang = document.getElementsByClassName("lang")[0];
langContainer.append(firstLang.cloneNode(true));
}
function removeLanguage() {
var langs = document.getElementsByClassName("lang");
if (langs.length > 1) {
langs[langs.length - 1].remove();
}
}
function removeAllAddedLanguages() {
var langContainer = document.getElementById('dynamic-select');
var firstLang = document.getElementsByClassName("lang")[0];
langContainer.innerHTML = firstLang.outerHTML;
}
<div id="dynamic-select">
<div class="lang">
<label for="dynamicSelect">
<select data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
</label>
<label for="proficiency">Level of proficiency
<select name="pLevel" id="pLevel">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
</div>
<button onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>
Why labels ? If you name the select correctly then this works
I left your inline event listeners but they could be moved to the script too. I change the buttons to type=button and gave the select an ID and used that
Also you had some illegal HTML (unclosed label)
// this code needs to be after the select is defined OR wrapped in an event listener
var x = document.getElementById("dynamicSelect");
var len = x.options.length; // default
function addLanguage() {
var lan = prompt("Language?","");
if (lan) {
x.options[x.options.length] = new Option(lan,lan)
x.selectedIndex=x.options.length-1;
}
}
function removeLanguage() {
if (x.options.length > 0) x.options.length--; // or x.options.length > len
}
function removeAllAddedLanguages() {
x.options.length = len;
x.selectedIndex=0;
}
<div id="dynamic-select">
<label for="dynamicSelect">Language spoken</label>
<select id="dynamicSelect" data-placeholder="Choose a Language...">
<option selected disabled value="">-- Choose a language --</option>
<option value="AF">Afrikanns</option>
<option value="SQ">Albanian</option>
<option value="AR">Arabic</option>
<option value="HY">Armenian</option>
<option value="EU">Basque</option>
<option value="BA">Bemba</option>
<option value="BN">Bengali</option>
</select>
<label for="proficiency">Level of proficiency</label>
<select name="pLevel" id="proficiency">
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Fluent</option>
<option value="fluent">Novice</option>
<option value="fluent">No knowledge</option>
</select>
</label>
</div>
<button type="button" onclick="addLanguage()" id="" class="action_button">Add A Language</button>
<button type="button" onclick="removeLanguage()" style="background-color: orange" class="action_button">Remove Last Added</button>
<button type="button" onclick="removeAllAddedLanguages()" style="background-color: red" class="action_button">Remove Added Languages</button>

javascript select hidden function issues

The issue I am having is the second select menu is not showing via the function.
I followed the [link][1] here and I am still not getting this to work
[enter image description here][2]
Update:
Tried to get more advance with this code and am having issues. The error I keep getting is:
"TypeError: Cannot read property 'style' of null
at scheduling (:7:20)
at HTMLSelectElement.onchange (https://null.jsbin.com/runner:1:298)"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div>
<form>
<p>Please do the following: <textarea> </textarea> <br /> <br /> Please do the follwing:</p>
<select id="actions" onchange = scheduling()>
<option value=" "></option>
<option value="report">Report</option>
<option value="schedule">Schedule</option>
<option value="research">Research</option>
<option value="go to">Go to</option>
</select>
<p><input type="submit" /></p>
</form>
</div>
<fieldset>
<div name = "Schedule">
<form id = scheduleProtocol style= "visibility:hidden">
<p> With who? </p> <textarea> </textarea> <br>
<p> Schedule what?</p>
<select>
<option value = "Breakfast"> Breakfast</option>
<option value = "Lunch"> Lunch</option>
<option value = "Dinner"> Dinner</option>
<option value = "A Call "> A Call </option>
</select>
<br>
<div name = "Schedule_Purpose">
<p> For what purpose? </p>
<select>
<option value="Catching Up"> Catching Up</option>
<option value="Building Relationship/s"> Building Relationships </option>
<option value="Sales">Sales</option>
<option value="Customer Success"> Customer Success</option>
<option value="Advice">Advice</option>
<option value="Learning">Learning</option>
<option value= "Team Building"> Team Building</option>
<option value= "Problem Solving"> Problem Solving</option>
<option value= "Funding/Investment"> Funding/Investment</option>
<option value = "Shared Goal/ Bucket List"> Shared Goal/ Bucket List</option>
<option value ="Relationship Maintenance"> Relationship Maintenance</option>
<option value ="Strategic Partnership"> Strategic Partnership</option>
</select>
</div>
<br>
<p> Where? </p>
<select>
<option value="to You"> Convenient to You </option>
<option value="to them"> Convenient to them </option>
<option value="both Parties">Both Parties</option>
</select>
<br>
<p>When?</p>
<select>
<option value="Exact Date">Exact Date</option>
<option value="Next Week"> Within the next week </option>
<option value="Next Two Weeks">Within the next two weeks</option>
<option value="Quarterly">Quarterly</option>
</select>
<br>
<br>
<input type = "submit">
</fieldset>
<div name = "Report Values">
<select>
<p> Report to me: when? </p>
<option value = "Monday">Monday</option>
<option value ="Tuesday"> Tuesday</option>
<option value = "Wednesday"> Wednesday</option>
<option value = "Thursday">Thursday</option>
<option value ="Friday"> Friday </option>
<option value = "Saturday"> Saturday</option>
<option value = "Sunday"> Sunday </option>
</select>
<br>
<p> At what time?</p>
<select>
<option value = "1 pm"> 1 pm</option>
<option value ="2 pm"> 2 pm</option>
<option value = "3 pm"> 3 pm</option>
<option value = "4 pm"> 4 pm</option>
<option value ="5 pm"> 5 pm </option>
<option value = "6 pm"> 6 pm</option>
<option value = "7 pm"> 7 pm</option>
</select>
</div>
</form>
</div>
<script>
function scheduling() {
var selectedItems = document.getElementById('actions');
var userInput = selectedItems.options[selectedItems.selectedIndex].value;
var scheduleProtcol = document.getElementById('scheduleProtcol');
if (userInput == "schedule") {
scheduleProtcol.style.visibility = "visible"; }
else {
scheduleProtcol.style.visibility = "hidden";
}
}
</script>
</body>
</html>
Here is the code:
<select id="list" onchange="return showApples()">
<option value="AL">Grapes</option>
<option value="NL">Apple</option>
</select>
<select id="AppleTypes"style="visibility:hidden">
<option value="GR">Granny</option>
</select>
<script>
function showApples()
{
var selectedItems = document.getElementById("list");
var userInput = selectedItems.options[selectedItems.selectedIndex].value;
if (userInput == "NL")
document.getElementById("AppleTypes").style.visibility = "visible";
else
document.getElementById("AppleTypes").style.visibility = "hidden";
}
</script>
function showApples(){
var selectedItems = document.getElementById("list");
var appleTypes = document.getElementById("AppleTypes")
var userInput = selectedItems.options[selectedItems.selectedIndex].value;
if (userInput == "NL"){
appleTypes.style.visibility = "visible";
}
else{
appleTypes.style.visibility = "hidden";
}
}
<form>
<select id="list" onchange="showApples()">
<option value="nothing"></option>
<option value="NL">Apple</option>
<option value="AL">Ball</option>
<option value="DL">Cat</option>
</select>
<select id="AppleTypes"style="visibility:hidden">
<option value="GR">Granny</option>
<option value="FU">Fuji</option>
</select>
</form>
Your Wrong code : <select id="list" onChange="return showApples()">
Should be changed like this : <select id="list" onchange="showApples()">
onChange => onchange

page is still reloading with event.preventDefault();

if the select drop-down menu has value of NULL, it should stop the page from loading. The jQuery works alerting the user of the issue, however the page still continues to the next page. Any assistance would be superb. Thanks
Luke
<fieldset class="form-group">
<label for="question-1">1. What age group are you?</label> <br>
<select class="drop-down" id = "ageChoice">
<option value="">Please Select</option>
<option value="16minus">16 or below</option>
<option value="16-18">16 to 18</option>
<option value="19-25">19 to 25</option>
<option value="26-34">26 to 34</option>
<option value="35-42">35 to 42</option>
<option value="43-50">43 to 50</option>
<option value="51-60">51 to 60</option>
<option value="61plus">61+</option>
</select>
</fieldset>
<input class="btn btn-primary" type="button" id= "next" value="Next" onClick="location.href='first-test.html' ">
$("#next").click(function () {
var age = $('#ageChoice');
if (age.val() === '') {
event.preventDefault();
alert("Please select your age group, thank you.");
}
else
return;
});
Ok, so because you have two click handlers, the event is being processed twice. The 'Default' you are trying to prevent is not the onClick="location.href='first-test.html' . That is being processed after your jQuery click function. So we take the onClick out of the html. and add the functionality to the jQuery click event (we could do it either way, but becuase you already have most of the code set up already we'll do it this way)
Here is the reworked code:
<fieldset class="form-group">
<label for="question-1">1. What age group are you?</label> <br>
<select class="drop-down" id = "ageChoice">
<option value="">Please Select</option>
<option value="16minus">16 or below</option>
<option value="16-18">16 to 18</option>
<option value="19-25">19 to 25</option>
<option value="26-34">26 to 34</option>
<option value="35-42">35 to 42</option>
<option value="43-50">43 to 50</option>
<option value="51-60">51 to 60</option>
<option value="61plus">61+</option>
</select>
</fieldset>
<input class="btn btn-primary" type="button" id= "next" value="Next">
and the jquery:
$("#next").on('click', function (event) {
var age = $('#ageChoice');
if (age.val() === '') {
alert("Please select your age group, thank you.");
} else {
location.href='first-test.html'
}
});

Calling mulitple user selections from dropdown form in javascript function

I am teaching myself how to code. I can't figure out how to take multiple values from an HTML drop down form and directly input them into a predefined function via javascript.(Form attributes?)
<form action="mywebsite.html">
<p> Month </p>
<select name="Bmonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<p> Day </p>
<select name="Bdom">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p> Year </p>
<select name="Byear">
<option value="2015">2015</option>
<option value="2014">2015</option>
<option value="2013">1988</option>
</select></form>
<script>
function DOB(Bmonth, Bdom, Byear) {
var z=Byear-Bmonth*Bdom;
return window.alert("Your number is " +z);
}
DOB(Bmonth, Bdom, Byear);
</script>
I simply want to take the three values that the user provides and enter them into the function DOB(Bmonth, Bdom, Byear); If I run the code like this it says "Bmonth is undefined."
You could also use a javascript framework or library that will make your life easier. For instance, with jQuery you would adapt your code like so:
<form action="mywebsite.html">
<p> Month </p>
<select name="Bmonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<p> Day </p>
<select name="Bdom">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p> Year </p>
<select name="Byear">
<option value="2015">2015</option>
<option value="2014">2015</option>
<option value="2013">1988</option>
</select></form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function DOB(Bmonth, Bdom, Byear) {
var z=Byear-Bmonth*Bdom;
return window.alert("Your number is " +z);
}
DOB(
$('[name="Bmonth"]').val(),
$('[name="Bdom"]').val(),
$('[name="Byear"]').val()
);
</script>
And with some further tweakings (adding a button to trigger DOB function and using ids instead of name): http://jsfiddle.net/neewonej/
First of all change name="" to id="" to make simpler with javascript selection. Which looks like this:
<form action="mywebsite.html">
<p> Month </p>
<select id="Bmonth">
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<p> Day </p>
<select id="Bdom">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p> Year </p>
<select id="Byear">
<option value="2015">2015</option>
<option value="2014">2015</option>
<option value="2013">1988</option>
</select></form>
You need to get the handle of the select box to tempElement variable using tempElement = document.getElementById("Bmonth"). Then get the selected index using tempElement.selectedIndex and make this index to retrieve value from tempElement.options. Use tempElement.options[tempElement.selectedIndex].value to get the value equivalent that user selects otherwise use tempElement.options[tempElement.selectedIndex].text to get the selected text.
Here is the working javascript code:
function DOB(Bmonth, Bdom, Byear) {
var z=Byear-Bmonth*Bdom;
return window.alert("Your number is " +z);
}
var tempElement = document.getElementById("Bmonth");
Bmonth = tempElement.options[tempElement.selectedIndex].value;
tempElement = document.getElementById("Bdom");
Bdom = tempElement.options[tempElement.selectedIndex].value;
tempElement = document.getElementById("Byear");
Byear = tempElement.options[tempElement.selectedIndex].value;
DOB(Bmonth, Bdom, Byear);
Thanks

Categories

Resources