Validation using Javascript and HTML

I'm having trouble displaying the "required" span text when a user fails to meet the field requirements in my code. It's not functioning correctly. Any idea what could be causing this issue?

function validate() {
  var spans = document.getElementsByTagName("span");
  var fname = document.registration.fname;
  if (fname.value === "") {
    spans[0].style.visibility = "visible";
  } else {
    spans[0].setAttribute("style", "visibility:hidden");
  }
}
<form name='registration' align='center'>
  <fieldset name='registration' class='fieldset-auto-width'>
    <div>
      <label for='fname'><b>FirstName:</b>
      </label>
      <input type='text' name='fname' placeholder='Enter First Name' value='' required='required' />
      <span id='errfn' class='error'> required</span>
    </div>
    <input type='button' value='Submit' onclick='validate();' />
  </fieldset>
</form>

Answer №1

After some investigation, I discovered the root of my issue. It turns out that I omitted a portion of my code, leading to confusion among some of you.

The main reason for the element not appearing was due to an additional span in my header section. In my JavaScript logic, I had defined spans as an array. Consequently, the span within the header corresponded to index span[0], while the span beneath the first name was span [1].

I appreciate the assistance provided nevertheless :)

Answer №2

Instead of initializing it to visible, why not start with hidden? By setting it to hidden initially, you can easily switch it to visible if needed when the user interacts with it.

function validate() {
  var spans = document.getElementsByTagName("span");
  var fname = document.registration.fname;
  if (fname.value === "") {
    spans[0].style.visibility = "visible";
  } else {
    spans[0].style.visibility = "hidden";
  }
}
<form name='registration' align='center'>
  <fieldset name='registration' class='fieldset-auto-width'>
    <div>
      <label for='fname'><b>FirstName:</b>
      </label>
      <input type='text' name='fname' placeholder='Enter First Name' value='' required='required' />
      <span id='errfn' class='error' style="visibility:hidden"> required</span>
    </div>
    <input type='button' value='Submit' onclick='validate();' />
  </fieldset>
</form>

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

Creating an autocomplete select dropdown for United States states in JS/Vue: A step-by-step guide

I am currently working with an array of state objects: states = [ {name: "California", abbreviation: "CA"}, {name: "New York", abbreviation: "NY"}, ] When using browser autocomplete, I have noticed that it functions properly when I set the v-mode ...

JavaScript: How come my closure isn't functioning properly?

In the provided code snippet, only the last value of .enter_form input is being assigned to the last MYAPP.list[0].responses[MYAPP.score.round].form[key], where the variable key is the only element that changes. This issue seems to be caused by passing o ...

The image fails to display when the Image tag in next.js is used

I have a picture in the public/img folder. I am trying to display it using the built-in <Image/> tag in next.js. This is the code I've written: <Image onClick={hideModal} alt="close_button" ...

When using Html5 mode with Angularjs and Express, the URL rewrite will always return the index page for

I have been searching for answers to a problem I am facing using similar questions. To utilize html5Mode with angularjs, it is necessary to inform the server on how to handle a direct visit to a page. The issue I am encountering is that when clicking on a ...

Tips for customizing the default styles of PrimeNG's <p-accordion> tag

Hello, I have encountered an issue with my html code snippet. I am attempting to create a tab with a label-header named "Users", but the accordion tag consistently displays it as underlined. <div class="ui-g"> <p-accordion id="tabsHeader"> ...

Uncertain about how to create a table with a fixed header as demonstrated

Can someone assist me in identifying the key styles necessary to create this fixed header table? I have found this example useful, but I am struggling to determine which styles are essential for achieving this effect. I am also curious about why a DIV and ...

Problem with scrolling in Firefox when inside an <a> block

My issue in Firefox is that I can't scroll by dragging the scrollbar within an <a> element: <a id="monther" class="single" href=""> <span>Month</span> <ul class="month" style="height:100px;width:200px;overflow:auto; ...

Is it possible to achieve avoidance of width calculation using only CSS?

Check out this link for more information. For a working version, visit: this site. The issue here is that Angular is calculating the width of the slider when the directive is processed, but since the item is not visible, it has no width. The labels on th ...

Ways to adjust dimensions depending on zoom level or screen size

Here is the HTML code snippet: <div id="divMainFirst"> <div id="divInnerFirst"> <div id="divTitleHeaderUC"> <span id="spanTitleHeaderUC">Urgent Care Wait Time</span> </d ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Div behaving as a radio input

I have customized radio buttons to look like buttons using JavaScript. However, on page load, both buttons automatically receive the 'active' class instead of only when they are selected. Additionally, the fadeToggle function in the if-statement ...

Python script for extracting data from tables by selecting various options from a dropdown menu

I'm currently attempting to extract data from this website: Although the default year is set to 2018, I am interested in scraping data for all available years on the site. A similar inquiry was raised four years ago, but the proposed solution does n ...

Develop a MySQL table using AJAX and HTML within a Cordova application

I've been developing an app using Cordova and I'm looking to create a feature where users can create and join different rooms to perform various actions. Despite trying multiple tutorials and scouring the internet, I'm struggling to understa ...

Does Vue.js interfere with classList.remove functionality?

When working with Vue.js, I encountered an issue where elements would briefly flash curly braces to the user before being hidden. To combat this problem, I implemented the following solution: HTML: <div class="main hide-me" id="my-vue-element"> ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Tips for capturing a redirect within a popup browser window?

I am currently developing a Chrome App that requires user authorization. For example, if a user wants to share a tweet on a website and clicks on a button, the app will first look for the user's access token in the Chrome storage. If the access token ...

Issues with jwplayer functionality

After downloading the necessary files and carefully following all instructions, I am still experiencing issues with the player not functioning as expected. <code> <html> <head> <script type="text/javascript" src="/jwpl ...

Can you explain the functionality of `node --harmony` please?

I recently encountered a node application that prompted me to run node with a harmony flag, using the command: node --harmony app.js Could someone explain what this harmony flag does and why the app can't function without it? I attempted to search ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Validating classes in Node.js using class-validator

I'm having some trouble with the class-validator package in my Node project. It's not being recognized and throwing an error. @MinLength(10, { ^ SyntaxError: Invalid or unexpected token Here's an example of what I'm doing: co ...