Utilizing a dropdown selection to trigger an IF statement in a function

I have an HTML code snippet as shown below:

The value "Test" is just for my reference to ensure that the code is functioning properly :)

<script>     

var tfa78 = document.getElementById("tfa_78").selvalue;

if( tfa78 == "karte" )
{
document.getElementById('tfa_2448').innerHTML ='<b>Bei karte anrufen.</b> <br>';
} else {
document.getElementById('tfa_2448').innerHTML ='Test';
}


I'm having trouble getting the desired result from this code. Could it be because I'm using the wrong method to select the dropdown value with the 'selvalue'? Previously, I used a similar code with a textfield and it worked fine, so I suspect there might be an issue with how I'm retrieving the value.

Thank you in advance for any help!

I made some updates to my code based on feedback:

 <script>     
 var tfa78 = document.getElementById("tfa_78").value;
 if( tfa78 == 'tfa_2438' ) {
 document.getElementById('tfa_2448').innerHTML ='<b> anrufen.</b> <br>';
 }else {
 document.getElementById('tfa_2448').innerHTML ='Test'+ tfa78;
 }
</script>

And here's the dropdown code which cannot be modified:

<select id="tfa_78" name="tfa_78" title="Quelle?" class="required"><option 
value="">Bitte auswählen:</option>
<option value="tfa_2438" id="tfa_2438" data-conditionals="#tfa_93" 
class="">karte</option>
<option value="tfa_2437" id="tfa_2437" data-conditionals="#tfa_93" 
class="">Test</option>
</select>

Answer №1

If you want to retrieve the chosen value, make sure to access the value property. As for selvalue, I am not sure if it is a valid term in any programming language. Here is an example for better understanding:

function update(){
  var userInput = document.getElementById("user_input").value;

  if( userInput == "option1" )
  {
  document.getElementById('result_output').innerHTML ='<b>Call option1 function.</b> <br>';
  } else {
  document.getElementById('result_output').innerHTML ='Test';
  }
}
<select id="user_input" onchange="update()">
  <option/>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

<div id="result_output"/>

Answer №2

 <script>
    var selectedOption = document.getElementById("tfa_78").options[document.getElementById("tfa_78").selectedIndex].value;
    if (selectedOption == "karte") {
        document.getElementById('tfa_2448').innerHTML = '<b>Make a call using the card.</b> <br>';
    } else {
        document.getElementById('tfa_2448').innerHTML = 'Test';
    }
</script>

Answer №3

Always remember to use .value over .selvalue;

var tfa78 = document.getElementById("tfa_78").value;

Here is the complete code snippet:

<script>     
    function updateMessage() {
        var tfa78 = document.getElementById("tfa_78").value;
        console.log(tfa78);
        if( tfa78 == "volvo" ){
            document.getElementById('tfa_2448').innerHTML ='<b>Call for map.</b> <br>';
        } else {
            document.getElementById('tfa_2448').innerHTML ='Test';
        }
    }

    </script>

    </head>

    <body>
    <select id="tfa_78" onchange="updateMessage()">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="fiat">Fiat</option>
      <option value="audi">Audi</option>
    </select>
    <div id = "tfa_2448"> </div>
    </body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The outcomes of my JavaScript code are not aligning with my expectations

I've been experimenting with printing objects from an API using JSON and AJAX, and I noticed that the console.log works perfectly to display the output. However, I'm having a bit of trouble with my generateCreatureDiv function as it doesn't ...

Viewing HTML web pages using Mozilla Firebox

Printing an HTML table with lots of content has been a challenge for me. Google Chrome didn't work, so I switched to Mozilla Firefox. However, now Firefox is breaking the page inside the table. My question is how can I trigger print preview in Firefox ...

“What is the process of setting a referenced object to null?”

Here is an example of the code I'm working with: ngOnInit{ let p1 : Person = {}; console.log(p1); //Object { } this.setNull<Person>(p1); console.log(p1); //Object { } } private setNull<T>(obj : T){ obj = null; } My objective is to ...

Automatically Dismissing a Bootstrap Alert After a Set Number of Seconds

Having some trouble closing a Bootstrap alert automatically on my new site built using the Bootstrap Framework. The issue arises when trying to close the alert after a certain amount of time. On the main page of the site, there is a modal login form. When ...

Using Javascript code within functions.php

I am facing an issue with the code below; function add_js_functions(){ $gpls_woo_rfq_cart = gpls_woo_rfq_get_item(gpls_woo_rfq_cart_tran_key() . '_' . 'gpls_woo_rfq_cart'); if(is_array($gpls_woo_rfq_cart)){ $count = count($gpls_woo_r ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Using Nuxt.js to import custom NPM packages on a global scale

The installation process for Nuxt's plugins/modules system can be quite intricate. Despite attempting to follow various suggestions, I have struggled to accomplish a seemingly simple task. After installing the NPM package csv-parse (which can be found ...

Regular expression for parsing any CSS font properties

Does anyone have a reliable regex to break down a css font string into its individual components? 12px arial italic bold sans-serif 12px/50px verdana etc ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

When attempting to use nodejs's collection.find() method with MongoDB, no response is received

I have been struggling to develop a node.js script that can retrieve only the records with a specific string key-value pair from a MongoDB collection containing around 30,000 documents. When I run this query on my MongoDB server, it gives me the exact res ...

Node and Web scraping Promise: a powerful combination

I've been using Cheerio and Node for web scraping, and I thought implementing promises could simplify handling asynchronous code. However, my attempt to chain promises hasn't been successful. Below is the code I'm working with, in hopes that ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

Warning: The DataTables alert has been triggered for table ID DimStatus. It is indicating that an unknown parameter, 'Code', has been requested for row 0 and column 0 during the initialization

https://i.stack.imgur.com/yEpSp.pngI am encountering an error while attempting to display my data in a datatable. The structure of my table is as follows: [Table("DimStatus", Schema = "dmg")] public class PolicyState { [Key] ...

After adding data to an empty array, index 0 becomes undefined for someEmptyArray

Currently, I am utilizing fs.readdir to generate an array of filenames within a specific directory. Additionally, I have implemented some regex functions to filter out undesirable filenames and/or filetypes. Upon executing the code provided below, I succe ...

Serve an image in Node.js from a location outside of the public folder

Is there a way to display an image that is located outside of the public folder in my webroot? Here is my directory structure: Webroot --core ----views ----public <- Stylesheets and other images are stored here ------index.ejs <- I want to display f ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

fetching numerous JSON documents using jquery

I am struggling to retrieve data from multiple JSON files and display it in a table. Despite being successful in appending data from one JSON file, I encountered issues when trying to pull data from multiple files. Here is my code: var uri = 'sharepo ...

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

Tips for accessing the values of fields in React Material UI components

When I console log the object, it shows: { "week":undefined, "name":undefined, "code":undefined } Additionally, is it appropriate to wrap all Material UI components in a form tag and treat the entire code as a form? Here is ...