Javascript dropdown menu value - javascript

I'm trying to access the value of a selected option in a drop down menu. I continuously am left with an "undefined" value.
Here is the HTML list I created:
function setDifficulty() {
var difficultySelector = document.getElementById("difficulty");
var difficulty = difficultySelector.selectedIndex;
if (difficulty.options[difficulty.selectedIndex].value == "0") {
window.alert("easy");
} else if (difficulty.options[difficulty.selectedIndex].value == "1") {
window.alert("medium")
} else if (difficulty.options[difficulty.selectedIndex].value == "2") {
window.alert("hard");
} else
window.alert(difficulty.value);
}
<select id="difficulty" onchange="setDifficulty();">
<option value="0">Easy</option>
<option value="1">Medium</option>
<option value="2">Hard</option>
</select>
What am I doing wrong?

The following code will work
function setDifficulty() {
var difficultyElt = document.getElementById("difficulty");
var value = difficultyElt.options[difficultyElt.selectedIndex].value;
if (value == "0") {
window.alert("easy");
} else if (value == "1") {
window.alert("medium")
} else if (value == "2"){
window.alert("hard");
}
}
Also, you may output your text value directly:
var difficultyElt = document.getElementById("difficulty");
var text = difficultySelector.options[difficultySelector.selectedIndex].text;
window.alert(text);

You can easily get a value from input. You don't need these tricky calculations of value. Also, when you want to work with specific values it's better to use switch-case. It seems much cleaner and needs less code.
function setDifficulty() {
var difficultySelector = document.getElementById("difficulty");
var difficulty = difficultySelector.value;
switch (difficulty) {
case "0":
window.alert("easy");
break;
case "1":
window.alert("medium");
break;
case "2":
window.alert("hard");
break;
default:
window.alert(difficulty.value);
}
}
<select id="difficulty" onchange="setDifficulty();">
<option value="0">Easy</option>
<option value="1">Medium</option>
<option value="2">Hard</option>
</select>

Related

Adding another option when the select dropdown is clicked?

I need to add a new select option in my HTML when they click it
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>
This new option is dynamic and will be coming from an API response... I'm parsing the var value from the API response but for now, I made it static just to test.
Right now, I have this:
$(document).ready(function () {
var k = 1
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var html = $(".statusButton").html();
if (k == 1) {
if (value == "Disable") {
new_v = "<option value='Disable' >Disable</option>";
}
else if (value == "Enable") {
new_v = "<option value='Enable' >Enable</option>"
}
var full = html + "" + new_v;
$(".statusButton").html(full);
k = 2;
}
});
});
It is working on JSFiddle but when I try to integrate it on my website, it's not reading it, even just the console log. WHat am I doing wrong?
I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).
Consider:
...
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var $statusButton = $(".statusButton");
if(k == 1){
if(value == "Disable")
{
$statusButton.append("<option value='Disable' >Disable</option>");
}
else if(value == "Enable")
{
$statusButton.append("<option value='Enable' >Enable</option>")
}
...
If you do things that way, you don't have to mess around with any extra .html calls.
This is short answer without creating too many variable.
$(document).ready(function() {
var k = 1
$(".statusButton").on('focus', function() {
var value = "Disable";
if (k == 1) {
if (value == "Disable") {
$(".statusButton").append("<option value='Disable' >Disable</option>");
} else if (value == "Enable") {
$(".statusButton").append("<option value='Enable' >Enable</option>")
}
k = 2;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>

The scripts that I made dont work and I can't find the problem

First of all, sorry, I know the next code is wrong, I'm new in programming and I have a problem with it. When the user select an option from the Select, a value it must change, then, the user must write a price in numbers which value must not be higher than the previous value, here is when the scripts should act but it doesn't works. The correct code must be something like that:
<script>
function cboc(){
var cb = $("#cbotipfon").val();
var maxvalGORE = null;
if(cb == 0){
maxvalGORE = 0;
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
}
function cbocc(){
var val = null;
var x = document.GetElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
document.GetElementById('txtprepos').value = "";
}
}
</script>
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon" onchange="cboc()">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" onblur="cbocc()" name="txtprepos" id="txtprepos"/>
I've been with that problem for days. If you can help me I'll be eternally grateful. Thanks in advance and for take your time.
Here is a simple example. No need to declare any function. Just declare your variables correctly and use the addEventListener method for getting the values of the input and select elements.
var maxvalGORE ,val ,cb ,x = null;
document.getElementById("cbotipfon").addEventListener("change", function(){
var cb = document.getElementById('cbotipfon').value;
if(cb == 0){
maxvalGORE = 0;
}
if(cb == 15){
maxvalGORE = 100;
}
if(cb == 16){
maxvalGORE = 200;
}
});
document.getElementById("txtprepos").addEventListener("change", function(){
x = document.getElementById('txtprepos').value;
val = parseInt(x);
if(val > maxvalGORE){
alert('The value is higher than $' + maxvalGORE +'.');
} else if(val == maxvalGORE) {
alert('The value is equal to $' + maxvalGORE +'.');
} else {
alert('The value is lower than $' + maxvalGORE +'.');
}
document.getElementById('txtprepos').value = "";
});
<select style="width=5.5em;" name="cbotipfon" id="cbotipfon">
<option value="0">Select</option>
<option value="15">Option A</option>
<option value="16">Option B</option>
</select>
<input type="number" name="txtprepos" id="txtprepos"/>

javascript - drop down display on the second field based on selection in first field

I have two fields customer category and customer type,
when I select one element in customer category , I need to display only a set of elements from customer type in the drop down and rest should not appear.
how do write it in javascript. Here is the one I tried but it doesnot yield proper result.
var custcategory = document.getElementById("custcatid");
var custtypes = document.getElementById('custtypeid').options;
alert('yes');
var n = custtypes.length;
var allowedtype;
if (custcategory.options[custcategory.selectedIndex].value == "ANALOGUE") {
alert('ANALOGUE');
allowedtype = 'CATV,CATV RURAL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "COMMERCIAL") {
alert('COMMERCIAL');
allowedtype = ' ,3ST HOTEL,4ST HOTEL,5ST HOTEL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DAS") {
alert('DAS');
allowedtype = ' ,DAS PHASE1,DAS PHASE2,DAS PHASE3,DAS PHASE4';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DTH") {
alert('DTH');
allowedtype = ' ,DTH';
}
var idx = 0;
for (var i = 0; i < n; i++) {
var type = custtypes[i].value;
var found = allowedtype.search(type);
if (found <= 0) {
custtypes[i].style.display = 'none';
}
else if (idx == 0) {
idx = 1;
document.getElementById('ctl00_uxPgCPH_custtype').selectedIndex = i;
}
}
alert('Done..!');
If I understand correctly, you are trying to filter a second select element based on what is selected in the first select element?
If so I put together the following snippet which might help you out. It can be probably be optimised further but it should help to get you started I feel.
(function () {
var CLASSES = {
categories: '.select__category',
types : '.select__types'
},
map = {
ANALOGUE: [
'CATV',
'CATV RURAL'
],
COMMERCIAL: [
'3ST HOTEL',
'4ST HOTEL',
'5ST HOTEL'
],
DAS: [
'DAS PHASE 1',
'DAS PHASE 2',
'DAS PHASE 3'
]
},
categorySelect = document.querySelector(CLASSES.categories),
typeSelect = document.querySelector(CLASSES.types),
filterTypes = function(val) {
// Based on a value filter the types select.
var opts = typeSelect.options,
allowedOpts = map[val];
typeSelect.value = allowedOpts[0];
for(var i = 0; i < opts.length; i++) {
if (allowedOpts.indexOf(opts[i].value) === -1) {
opts[i].hidden = true;
} else {
opts[i].hidden = false;
}
}
};
filterTypes(categorySelect.value);
categorySelect.addEventListener('change', function(e) {
filterTypes(this.value);
});
}());
<!DOCTYPE html>
<head></head>
<body>
<select id="categories" class="select__category">
<option value="ANALOGUE">Analogue</option>
<option value="COMMERCIAL">Commercial</option>
<option value="DAS">Das</option>
</select>
<select id="types" class="select__types">
<option value="CATV">Catv</option>
<option value="CATV RURAL">Catv Rural</option>
<option value="3ST HOTEL">3st Hotel</option>
<option value="4ST HOTEL">4st Hotel</option>
<option value="5ST HOTEL">5st Hotel</option>
<option value="DAS PHASE 1">Das Phase 1</option>
<option value="DAS PHASE 2">Das Phase 2</option>
<option value="DAS PHASE 3">Das Phase 3</option>
</select>
</body>
If you run the snippet, you'll see that making changes to the first will update the second select accordingly based on the defined map.
Hope this can help you out!

Select Box onchange Update Multiple Items

I am trying get a select box to use the onchange function to update multiple items surrounding it. Here is my code so far:
function picture() {
var imglink;
var imgprice;
var picture_type = document.getElementById('picture_type').value;
if ("picture_type" == "1") {
imglink = "img1.png";
imgprice = "$xx.xx";
}
if("picture_type" == "2") {
imglink = "img2.png";
imgprice = "$xxx.xx";
}
else {
document.getElementById('iphoneprice').style.display = 'none';
}
document.getElementById('phoneimg').src = imglink;
document.getElementById('iphoneprice').innerHTML = imgprice;
}
And the matching HTML:
<select id="picture_type" onchange="picture()">
<option value="1">iPhone 4</option>
<option value="2">iPhone 4S</option>
</select>
<p id="iphoneprice"></p>
<img id="iphoneimg" src="" />
How could I make it successfully update these two variables simultaneously?
You have a typo (getElementById('phoneimg') should be getElementById('iphoneimg')) and quotes around variable names. This should work:
function picture() {
var imglink;
var imgprice;
var picture_type = document.getElementById('picture_type').value;
if (picture_type == "1") {
imglink = "img1.png";
imgprice = "$xx.xx";
}
else if(picture_type == "2") {
imglink = "img2.png";
imgprice = "$xxx.xx";
} else {
document.getElementById('iphoneprice').style.display = 'none';
}
document.getElementById('iphoneimg').src = imglink;
document.getElementById('iphoneprice').innerHTML = imgprice;
}
jsFiddle example

Adding Option to Drop Down Value if it doesn't exist?

How can the code below be modified so as to allow a new value to be added to the drop down list, should the specified value not be found in the found in the drop down box?
Right now, I use the given function below to find a given value (option_name) in a drop down box.
I'd like to modify the negative flag (!flag) so as to instead of alerting me that it not has found the option_name, to basically add the new option_name in the existing drop down list.
ie.
get_position( 'drop', 'flower' )
<select id="drop" style="width: 200px;">
<option value="0"></option>
<option value="1">apples</option>
<option value="2">oranges</option>
<option value="3">pears</option>
<option value="4">mangos</option>
<option value="5">bananas</option>
<option value="6">kiwis</option>
</select>
function get_position(id,option_name) {
var flag = false;
for ( var i=0; i <= document.getElementById(id).options.length - 1; i++ ) {
if (document.getElementById(id).options[i].text === option_name) {
document.getElementById(id).selectedIndex = i;
flag = true;
}
}
}
you can use return false if any match found then add the record
function get_position(id,option_name) {
var flag = false;
var length=document.getElementById(id).options.length;
for ( var i=0; i <= length - 1; i++ ) {
if (document.getElementById(id).options[i].text == option_name) {
document.getElementById(id).selectedIndex = i;
return false;
}
}
//add item on drop down now
document.getElementById(id).options[length] = new Option( txt, length );
document.getElementById(id).selectedIndex = length;
}
if you can use Jquery then some thing like this
if($("#id option:contains('option_name')").length ==0)
{
$("#id").append(new Option("option text", "value"));
}

Categories