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

Why does the method Array.concat on an extended class remove empty values in Node.js version 8.9.3?

I am experimenting with adding new functionality to Arrays in node.js without altering the original Array class to avoid any unintended consequences in other modules. During testing, I encountered some failures which led me to discover that the behavior o ...

The WebSocket function is returning undefined even though it successfully fetches the user; however, the user is

I've been experimenting with a websocket to retrieve user information. When I establish the connection and send messages to receive the data, it returns undefined when I try to use that information elsewhere. However, if I run console.log within the ...

Modify the heading color of elements in a class to a distinct color when the cursor hovers over the element

I currently have 3 heading elements: elem1, elem2, and elem3. When I hover over elem1, I want elem1 to turn yellow and elem2 and elem3 to turn purple. If I hover over elem2, I want elem2 to be yellow and the others to be purple. Once I release the hover, I ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

How can you transform a nested array into a flat JavaScript map?

If we consider a JavaScript Map structured like this: [ { id: 1, name: "Foo", contents: [1,2,3], morecontents: ["a","b"], }, { id: 2, name: "Bar", c ...

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...

Utilize ng-checked in AngularJS to bind all values from an array to checkboxes

I'm working on a project where I need to bind the name and age of a person using checkboxes, with the data looped through ng-repeat. However, I seem to be able to only get the "name" from the array, not the "age". Can someone please help me find my mi ...

Merging pertinent information from separate arrays

Seeking assistance in merging data from two distinct arrays with varying structures. Data is acquired via API, the initial request: [ { "category_id": "12345", "category_name": "itemgroup 1", "cat ...

Substitute for SendKeys() in Angular JS web pages using Selenium

Currently, I am utilizing selenium automation to streamline the processes of a third-party website. To input data into form fields, I have been employing the SendKeys() method. While this method is functional, it's time-consuming as there are numerous ...

Loop through data and use jQuery to insert it into the server

I am encountering an issue with my code as I attempt to insert data from a loop; unfortunately, I keep getting the error message "Uncaught TypeError: Illegal invocation". window.items = ''; _.forEach(cart.items, function(n, key) ...

"Optimizing Performance: Discovering Effective Data Caching

As a developer, I have created two functions - one called Get to fetch data by id from the database and cache it, and another called POST to update data in the database. However, I am facing an issue where I need to cache after both the get and update oper ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Guide to showcasing associated information in HTML using Angular 7

I am a beginner with Angular 7 and I am attempting to showcase a product's color on the HTML side using Angular 7 but have not been successful. Below are my tables; Product Id Name Color Id Name ProductColorRelation Id ProductId ColorId In ...

I am unfamiliar with this specific JavaScript algorithm problem from Codewars

I need help with a JavaScript algorithm question This problem involves extracting two letters from the middle of odd-numbered characters My confusion lies in function getMiddle(s) { //Code goes here! let answer = ""; if (s.length % 2 !== 0) { a ...

Using Flask to Render Templates with Repeated HTML Components

I am currently working on integrating a Flask app with JS. My app.py file has the following code: import urllib import requests import time from es import book from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route( ...

What is the best way to set values for the outcomes of a jQuery/AJAX post?

When sending data to a php page using jquery, I aim to receive the response from the page and store it in php variables on the original page without displaying results in the HTML or appending a DIV. Here's an example of how this can be achieved: Sam ...

Unable to zoom in on D3 Group Bar Chart

I've designed a group bar chart and attempted to implement zoom functionality. However, I noticed that the zoom only works for the first group of bars and not for the entire chart. Any assistance on this matter would be highly appreciated. Thank you i ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

Utilizing the power of AWS Lambda in conjunction with moment JS to generate unique

My current time zone is GMT+8, and the AWS region I am using is Singapore (ap-southeast-1). I am facing an issue where there are discrepancies in date calculations between my local machine and when I deploy my code on AWS Lambda. My goal is to ensure that ...