Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page.

However, my second code attempt aims to toggle the visibility of a div element based on user selection but it doesn't seem to be working. Can anyone provide guidance or point me in the right direction? Appreciate any help provided.

<!DOCTYPE html>
<html>
<head>
  <title>getElementById example</title>
  <script>
  function changeColor(newColor) {
    var elem = document.getElementById("para1");
    elem.style.color = newColor;
  }
  </script>

  <script>
       // EXPAND
    function Hide(elementid){
        document.getElementById(elementid).style.display = 'none';
    }

    function Show(elementid){
        document.getElementById(elementid).style.display = '';
    }
  </script>

</head>
    <body>
        <p id="para1">Some text here</p>
        <button onclick="changeColor('blue');">blue</button>
        <button onclick="changeColor('red');">red</button>

        <div id="one">ONE</div>
        <div id="two">TWO</div>

        <select>
            <Option value="javascript:Show('one');javascript:Hide('two')">one</option> 
            <Option value="javascript:Hide('one');javascript:Show('two')">two</option>
        </select>
    </body>
</html>

Answer №1

The value attribute does not trigger JavaScript functions.

To achieve this functionality, you must assign a change event to the select element and then evaluate the selected value to decide which content to display or hide.

Here is an example:

<div id="one">ONE</div>
<div id="two">TWO</div>
<div id="three">THREE</div>

<select>
    <option>one
    <option>two
    <option>three
</select>

<script>
  function show(id) {
    document.getElementById(id).style.display = '';
  }
  function hide(id) {
    document.getElementById(id).style.display = 'none';
  }
  function determineDiv(event) {
    var select = event.target;
    var options = select.options;
    for (var i = 0; i < options.length; i++) {
      var option = options[i];
      if (option.selected) {
        show(option.value);
      } else {
        hide(option.value);
      }
    }
  }

  document.querySelector('select').addEventListener('change', determineDiv);
</script>

Answer №2

My suggestion would be to utilize the block method, like this:

document.getElementById(elementid).style.display = 'block';

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

What is the best way to change routes within my React application?

I am currently facing a challenge with the Routes in my work's web application. The existing method of accessing routes involves manually typing in the extended path in the browser, which is not ideal. I want to enhance this by adding new routes that ...

Boosting Your SCSS (SASS) Productivity

I'm curious if there are any ways to make the code below more efficient or dynamic. I've already achieved the desired result, but I'm interested in optimizing it further. The Script Any suggestions would be highly appreciated, Cheers, ...

Navigational dropdown menu item vanishing upon hover

Utilizing bootstrap for my website, the main navigation employs dropdowns for secondary choices. I am encountering an issue in IE10 only (works fine everywhere else) where the dropdown menu is inconsistently accessible. Additionally, if you manage to acce ...

Working with Firestore database in React Js may result in an infinite loop

I have connected my React JS app to Cloud Firestore and I am facing an issue with displaying the objects in my JavaScript file. Even though I only have one object in Firestore, it seems to be reading in a loop and I can't seem to identify the cause. ...

What is the preferred method of compiling Sass: utilizing the Live Sass Compiler extension in VS Code, or setting up and running Sass through npm? (Including guidance on transitioning from node-sass to dart-sass)

As I delve into an online course focused on Advanced CSS and Sass, I have noticed that the techniques being taught seem a bit outdated. The course heavily relies on node-sass in its dependencies, which is now considered deprecated. An alternative solution ...

Conceal information within a label

I am encountering an issue with a wordpress plugin and I am attempting to conceal (or alternatively, replace which would be fantastic) the terms "DD", "MM" and "YYYY" in the provided code: <div class="smFormInlineFormCont"> <div class="smInli ...

Firebase Firestore is returning the dreaded [object Object] rather than the expected plain object

I've created a custom hook called useDocument.js that retrieves data from a firestore collection using a specific ID. However, I'm encountering an issue where it returns [object Object] instead of a plain object. When I attempt to access the nam ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Different approach in Vuejs for selecting target/currentTarget in a list

I have my current configuration set up as depicted below: [{ name: "test", tags: ["aa","bb","v"] }, ...] <div class="item" v-for="item in sdList" :data-id="item.id"> <span @click="deleteTag(item, $event)" v-for="tag in item.tags ...

`Problem with the layout of the form on the website`

Experiencing some challenges with the container design for a job sheet project. As a beginner, I have been learning on the fly and following online tutorials to create functional forms. However, this particular form is not rendering correctly when viewed o ...

Toggle the functionality of the login button in foundation

I am currently utilizing the front-end framework Foundation. My question is, how can I modify this menu so that the Log in button is only enabled when both the Login and Password input fields are filled with text? <form data-abide="ajax"> <div ...

What is the method for determining the required or imported base path?

My package.json includes the main option to set the default file for importing like import 'my-index' from 'my-module' However, I would like to break up my-module into separate files so developers can include them individually with sta ...

What is the best way to identify the appropriate class name for searching in Selenium?

I'm currently on a mission to find an element based on its class name. I have extracted this snippet from the page source (which I saved as a file using BeautifulSoup): <div class="flex flex-column"><div... If I attempt to pinpoin ...

When viewing my website on a mobile device in landscape mode, the CSS divs sized at 20% do not match the size of the div set at

Currently, I am working on a mobile application that is HTML5 cross-platform compatible. To design the app, I am utilizing Bootstrap 3, although it seems unrelated to the specific issue I am facing. Here's the problem at hand: Within my application, ...

The responsive class seems to be malfunctioning within the Laravel 5.3 framework

I have a project that involves Laravel and Vue.js. In my Laravel project, I am importing Bootstrap CSS using the following line: // Bootstrap @import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; This import is done in the app.scss file. ...

Creating a Chrome extension with Angular 5: A comprehensive guide

Currently, I am in the process of developing a Chrome extension using Angular 5. Initially, I successfully created a basic Angular app with the help of Angular Material and it functioned perfectly as an Angular application (I used ng build for verification ...

Challenges with Cross-Origin Resource Sharing (CORS) when accessing Uber API OAuth

I am encountering an issue while attempting to make client-side JS calls to Uber API endpoints that require the OAuth Bearer token, such as /v1/me. The problem arises due to the absence of the Access-Control-Allow-Origin header in the response. I have suc ...

Fade effects on hover with a changing background color

Here is the CSS code to be used: #onec-fourth:hover { background-color: #F36DE1; color: white; } I am looking to keep the background color and text color effects for 1 second after I move my mouse off the object (#onec-fourth). Currently, when I mov ...

Safari displays an inexplicable gray border surrounding the <img/> element, despite the actual presence of the image

https://i.stack.imgur.com/4QR52.png There is an unexpected gray border visible around the dropdown image, as seen above. This occurrence has perplexed me because, according to several other queries, this problem arises when the image's src cannot be ...

Missing or Lost Values in Object-Oriented PHP Arrays

I am fairly new to object-oriented PHP and PHP in general. I have a class where I assign array values in the constructor, but later when I try to access the array, it shows as null. Any ideas why this might be happening? Could it be an issue with scope? c ...