Invisible tag remains unseen

I need to dynamically hide some text and show specific labels upon clicking a button. How can I achieve this?

<body>
        <div id="middle">
            <div id="left">
            </div >
            <div id="m">
            Name: <input type="text" name="y1"><br />
            Family: <input type="text" name="y1"><br />
            Phone: <input type="text" name="y1"><br />

            <label style="display: none "  name="y2" >A </label>
            <label  style="display: none " name="y2" >B </label>
            <label style="display: none " name="y2" >C </label>
            <button  onclick="myFunction()">Hide elements</button>

            <script>
            function myFunction() {
              var x = document.getElementsByName("y1");
              for (var i = 0; i < x.length; i++) {
                x[i].style.display = "none";
              }
              var x = document.getElementsByName("y2");
              for (var i = 0; i < x.length; i++) {
                x[i].style.display = "visible !important"; 
              }
            }
            </script>
    </div>
    </body>

Answer №1

The reason for this issue is that the display CSS property is not set to visible. The correct value for display should be inline when used for a label.

In addition, it seems like there is a misuse of the label element in your code. The label element should be associated with a form field, which is missing in your implementation. Consider using span elements instead.

Avoid inline styles and event handlers. It's recommended to use CSS classes for styling and keep all scripting within the script tag.

.hidden { display:none; }
Name: <input type="text" name="y1" class="hidable"><br>
Family: <input type="text" name="y2" class="hidable"><br>
Phone: <input type="text" name="y3" class="hidable"><br>

<span class="hidden y2">A</span>
<span class="hidden y2">B</span>
<span class="hidden y2">C</span>
<button>Hide elements</button>

<script>
  // Get the inputs and spans into their own Arrays
  let inputs = Array.prototype.slice.call(document.querySelectorAll("input.hidable"));
  let spans = Array.prototype.slice.call(document.querySelectorAll("span.y2")); 
              
  // Set up the click event handler in JavaScript, not in HTML
  document.querySelector("button").addEventListener("click", hideShow);
              
  function hideShow() {
    // Loop over the inputs
    inputs.forEach(function(input){
      input.classList.add("hidden"); // Hide the input
    });
                
    // Loop over the spans
    spans.forEach(function(input){
      input.classList.remove("hidden"); // Show the span
    });
  }
</script>

Answer №2

Are you looking for this specific solution?

function myFunction() {
  var x = document.getElementsByName("y1");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  var x = document.getElementsByName("y2");
  for (var i = 0; i < x.length; i++) {
    x[i].style.display = "inline";
  }
}
<div id="middle">
  <div id="left">
  </div>
  <div id="m">
    Name: <input type="text" name="y1"><br /> 
    Family: <input type="text" name="y1"><br /> 
    Phone: <input type="text" name="y1"><br />

    <label style="display: none " name="y2">A </label>
    <label style="display: none " name="y2">B </label>
    <label style="display: none " name="y2">C </label>
    <button onclick="myFunction()">Hide elements</button>

  </div>
</div>

If this is what you have in mind, keep in mind that the display property has multiple values other than inline. It might be helpful to learn more about CSS Layouts. Check out this link to get started: https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout

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

Troubleshooting PHP webpage with dysfunctional Python AJAX functionality

I have been working on developing a website that integrates with a python script to control GPIO pins on my Raspberry Pi. Unfortunately, I've encountered some issues with the code and need some assistance in troubleshooting. Could someone please revi ...

Executing functions from main component in tanstack table operations

One of the reusable React components I have is: "use client"; import { useState } from "react"; import { ColumnDef, flexRender, ColumnFiltersState, getFilteredRowModel, getCoreRowModel, getPaginationRowModel, ...

Iterate through a collection of JSON objects using JavaScript

Hello, I'm a beginner in Javascript and I am currently attempting to iterate over an array of JSON objects. However, I am facing issues with the code below that was designed to loop through a static array of JSON constants. function saveAccount() { ...

Vue watchers capturing original value prior to any updates

When working with Vue.js, we can easily access the value after modification within watchers using the following syntax: watch: function(valueAfterModification){ // ...... } But what about getting the value before it's modified? PS: The official ...

Concealing specific outcome by implementing jQuery and AJAX with a database

I have an HTML list that appears as follows: <ul> <li>something</li> <li>something1</li> <li>something2</li> <ul> <div class="randomwrapper"> <img src="<?php echo $databaseresult[$i];?& ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Hiding horizontal lines in a table without affecting vertical lines (Material-ui) - a step-by-step guide

Is there a way to hide the horizontal lines and timeslots in the table below without affecting the vertical lines? I attempted to use the visibility property on the td elements, but it hides both sets of lines. Any suggestions on how to resolve this is ...

Using Jasmine to simulate multiple method calls in a testing environment

Currently, I am working on writing a JavaScript test for a method that involves making two function calls (model.expandChildren() and view.update();). // within the 'app' / 'RV.graph' var expandChildren = function(){ return model.e ...

Solving data within an Angular Controller

Recently delving into Angular development, I've found myself caught in a loop trying to solve this particular issue. To give some context, I'm utilizing the MEAN stack through mean.io which includes Angular UI Router functionalities. In my data ...

How to display two elements side by side within a div using React

I have an array that looks like this: const arr = [1,2,3,4,5,6,7,8,9,10] I am looking to display the elements in pairs per line within two-dimensional divs. Here is what I have in mind: This represents the main React element: render() { return <di ...

exploring asynchronous javascript behavior utilizing the sleep/setTimeout function in the context of THREEJS and Angular

As a newcomer to Javascript and asynchronous programming, I am facing what I believe to be a beginner's issue. I have been using ThreeJS to create a scene with multiple objects (approximately 100) and everything was working smoothly until now. My cu ...

What is the best way to implement a dynamic Menu Component in next.js?

Hello friends! I am currently working on a Next.js web app with a Menu Component that fetches data dynamically through GraphQL. I really want to achieve server-side rendering for this menu component. My initial attempt to use getStaticProps() to render the ...

Using the Javascript jQuery post() or get() method to pass a JSON object within a closure function prior to

Looking for the optimal approach to managing a JSON object that needs to be posted/retrieved upon document readiness in order to execute another function that constructs the DOM based on said JSON object. This JSON object also undergoes updates every 30 se ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

The POST function is executed twice, with the first attempt resulting in a failed API call, but the second attempt is

I am experiencing issues with my subscribe dialog, as it seems to be running the API call twice. The first time it fails, but on the second attempt, it succeeds and inserts the email into the database. This double run is causing errors in my AJAX function, ...

What is the best way to include a .wav file within a PHP if statement?

I am new to PHP and coding in general, so please bear with me if I sound inexperienced. I am attempting to play a WAV file from a PHP if statement. However, when I try to echo the HTML for the sound, I encounter this error: PHP Parse error: syntax error, ...

Expandable Grid with UI-GRID - Automatically expand a row when clicked on

I prefer not to utilize the default + icon for expanding the row. The row should expand when clicked anywhere on it. I attempted the following: HTML <div ui-grid="gridOptions" ui-grid-expandable class="grid"> Controller var app = angular.module( ...

What is the best way to integrate Emotion styled components with TypeScript in a React project?

Currently, I am delving into TypeScript and attempting to convert a small project that utilizes Emotion to TypeScript. I have hit a roadblock at this juncture. The code snippet below export const Title = styled.div(props => ({ fontSize: "20px", ...

Exploring Vue.prototype attributes and utilizing them

I'm facing a challenge while attempting to globally set a property using Vue.prototype. This is what I currently have: microsoftTeams.initialize(); microsoftTeams.getContext((context) => { Vue.prototype.$teamsContext = true; }); new Vue({ ...

Adding a button to the right of a text-field input in Vuetify app

I need advice on the best way to use Vuetify in order to display a button to the right of a text-field (attached). I've checked the main site for information but couldn't find anything related to this specific scenario. https://i.sstatic.net/Pp ...