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

Is it possible to nest clicks for ajax calls within the results of a previously appended call?

As I dive into learning about AJAX to enhance page loading speed by avoiding reliance on PHP for displaying results, I've encountered a challenge. I have three tiers of data distributed across three database tables: The first tier of data is fetche ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

SVG with complete coverage of width and height

Here's the challenge: create a full window svg image with aspect distortion without using an SVG tag. Why avoid the SVG tag? Because I plan to replace the SVG later on (possibly frequently) and haven't found a simple way to do so. Previous attem ...

Efficient Error Handling in Next.JS with Apollo GraphQL Client

Although the component successfully renders the error state, an uncaught exception is displayed in the console and a dialogue box appears in the browser. How can expected errors be handled to prevent this behavior? import { useMutation, gql } from "@a ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

Retrieve a boolean value through an Ajax call from a C# function using T4MVC

I have a search bar on my website with the following code: <form onsubmit="return IsValidCustomer()"> <input class=" sb-search-input" placeholder="Search for a customer..." type="text" value="" name="search" id="search"> <input cl ...

Conceal specific image(s) on mobile devices

Currently, I am facing an issue on my website where I need to hide the last two out of six user photos when viewed on mobile or smaller screens. I believe using an @media code is the solution, but I'm unsure about the specific code needed to achieve t ...

What is causing the return statement to not function properly in the Mongoose findOne method?

I am attempting to locate an item by its name, then update the table and return the updated result. However, the return statement is not working as expected in my code: class addSongsToArtist { constructor(artistName) { Artist.findOne({ ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

What are the recommended margins for various alphabets?

When displaying text, some alphabets take up more space than others. So how can I adjust the white space between elements '#re1' and '#re2' automatically in the scenario described below? In this code snippet, what is the best way to ad ...

Having trouble transferring files to an unfamiliar directory using Node.js?

const { resolve } = require("path"); const prompt = require('prompt'); const fsPath = require('fs-path'); // Retrieve files from Directory const getFiles = dir => { const stack = [resolve(dir)]; const files = []; whi ...

Method in Vue.js is returning an `{isTrusted: true}` instead of the expected object

I am having an issue with my Vue.js component code. When I try to access the data outside of the 'createNewTask' function, it renders correctly as expected. However, when I attempt to log the data inside the function, it only returns {isTrusted: ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...

Utilizing the child element's attribute value in a list to dynamically modify the CSS styling of a div element

I'm struggling with designing a ranking bar that consists of 9 bars. I want the height of the bars to vary, with bar 0 and bar 8 being the longest. However, I am having difficulty manipulating my jQuery selector to change the CSS style of the bars bas ...