The Javascript validation error for radio buttons briefly appears for a moment when it should stay visible

After reviewing about 30 examples and testing them out, I have decided to post my question since none of the examples seem to be working for me.

I am not an expert in JavaScript, but I assumed that validating a simple radio button should not be too difficult.

I am attempting to display a nice CSS error message when the form is incorrect. However, for some reason, the radio button error message appears for less than a second and then disappears. The other errors (non-radio) seem to work fine. For this question, I will only post the code related to the radio button part.

The HTML:

<div align="left"><form name="myForm" method="post" style="display:inline" onsubmit="return(validate());"> 

<div class="radio">
<input type="radio" class="radio" name="automatisering" value="1">Automatisering
<input type="radio" class="radio" name="automatisering" value="2">Software
<div id="Fout" style="display:none" color="white"></div>
</div>

<input type="submit" value="Submit" />   
</form></div>

The validation block:

function validate()
{

    if(document.myForm.automatisering[0].checked != true && document.myForm.automatisering[1].checked != true) 
   {
     document.getElementById("Fout").style.display = 'inherit';
     document.getElementById("Fout").setAttribute("title", "Some error message");    
     document.myForm.automatisering.focus() ;
     return false;
   } 
   else
   {
     document.getElementById("Fout").style.display = 'none';
   }

~~~~~Other validations for text, email, phone, etc. that are working. All starting with an if statement and returning false with a div displaying errors.

return( true );
}

Here are the approaches I tried that did not work - the error message appears for less than a second when it should not disappear:

1# Based on a solution I found:

var elem=document.forms['myForm'].elements['automatisering'];
    len=elem.length-1;
    chkvalue='';
    for(i=0; i<=len; i++)
    {
        if(elem[i].checked)chkvalue=elem[i].value;  
    }
    if(chkvalue=='')
    {
    document.getElementById("Fout").style.display = 'inherit';
     document.getElementById("Fout").setAttribute("title", "Some error message!");   
     document.myForm.automatisering.focus() ;
    return false;
    }
    document.getElementById("Fout").style.display = 'none';

2# Based on the predefined values of the radio buttons:

if(document.myForm.automatisering.value != 1 && document.myForm.automatisering.value != 2) 
   {
     document.getElementById("Fout").style.display = 'inherit';
     document.getElementById("Fout").setAttribute("title", "Some error message!");   
     document.myForm.automatisering.focus() ;
     return false;
   } 
   else
   {
     document.getElementById("Fout").style.display = 'none';
   }

3# Based on the array of the radio buttons:

if(document.myForm.automatisering[0].checked != true && document.myForm.automatisering[1].checked != true) 
   {
     document.getElementById("Fout").style.display = 'inherit';
     document.getElementById("Fout").setAttribute("title", "Some error message!");   
     document.myForm.automatisering.focus() ;
     return false;
   } 
   else
   {
     document.getElementById("Fout").style.display = 'none';
   }

Regardless of the approach, the error message displays for 0.5 seconds and then disappears. I even tried removing the display = 'none' in the else statement, but the issue persists.

Answer №1

The following code snippet is incorrect:

document.myForm.automatisering.focus() ;

The element document.myForm.automaterising is a NodeList, which means you can only focus on a specific DOM element. Any error in this code does not trigger return false, resulting in the form being submitted unintentionally.

Consider revising the code to:

document.myForm.automatisering[0].focus() ;

Answer №2

Currently, it's actually functioning for me. I managed to resolve a syntax error in your HTML where the input was missing its opening tag. You can view the corrected code here: http://codepen.io/anon/pen/PwRXbr

UPDATE:

The main problem lies in the onsubmit method not preventing the form from being submitted even when you return false. One workaround is to create a button that verifies the values and then triggers document.myForm.submit(). Here's an example demonstrating this solution: http://codepen.io/anon/pen/ZYxVJy

Below is the corrected code snippet:

<div align="left">
  <form name="myForm" action="#" style="display:inline" onsubmit="return(validate());"> 
    <div class="radio">
      <input type="radio" class="radio" name="automatisering" value="1">Automatisering
      <input type="radio" class="radio" name="automatisering" value="2">Software
      <div id="Fout" style="display:none" color="white">bla</div>
    </div>
    <input type="submit" value="Submit" />   
  </form>
</div>

Javascript Section

function validate()
{
    if(document.myForm.automatisering[0].checked != true && document.myForm.automatisering[1].checked != true)
   {
     document.getElementById("Fout").style.display = 'block';
     document.getElementById("Fout").setAttribute("title", "Some error message");
     document.myForm.automatisering.focus() ;
     return false;
   } 
   else
   {
     document.getElementById("Fout").style.display = 'none';
   }

return true;
}

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

Tips on preventing the initial undefined subscription in JavaScript when using RxJS

I am having trouble subscribing to an object that I receive from the server. The code initially returns nothing. Here is the subscription code: ngOnInit() { this.dataService.getEvents() .subscribe( (events) => { this.events = events; ...

Using HTML and JavaScript to create a link that appears as a URL but actually directs to a JavaScript function

I am working on an HTML page and I am trying to create a link that appears to go to 'example.html' but actually goes to 'javascript:ajaxLoad(example.html);'. Here is what I have tried: <a href="example" onclick="javascipt:ajaxLoad( ...

Need help with JQuery mouseOver fading in twice when you only want it to fade in

The version can be displayed here. I'm looking to have the current text fade away and the new text fade in. Strangely, it seems to fade in twice for some reason. $(window).load(function(){ var originalTitle = $('.Pinctitle').text(); $(&apo ...

jQuery setInterval is not functioning as expected

I need help comparing two password fields and displaying a Popover message if they do not match. HTML <div class="form-group col-lg-6"> <label>Password</label> <input type="password" class="form-control" name="password" id="p ...

Accessing the initial element inside a DIV using CSS

In the structure of my code, I have a WYSIWYG editor enclosed in a table within a div element: <div class="mydiv"> <li> <table>My WYSIWYG</table> </li> </table> Within the WYSIWYG editor itself, there a ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

Styling CSS: Create circular images with dynamic text positioning or resizing on screens larger than 768px

I'm struggling to figure out how to create a circular profile picture on a background image that remains responsive and maintains its position across different screen sizes. Currently, I've been using fixed margin values to adjust the position, ...

Why am I struggling to properly install React?

C\Windows\System32\cmd.e X + Microsoft Windows [Version 10.0.22621.2715] (c) Microsoft Corporation. All rights reserved. C:\Users\user\Desktop\React>npx create-react-app employee_app npm ERR! code ENOENT npm ERR! s ...

How to reference global Sass variables in a Sass module

My preferred method involves utilizing a global .scss file that houses all the foundational styles, such as primary color selections. Following this, I create separate modules for each React Component to maintain organization and reduce the need for import ...

The use of the tooltip function in Rails 6 webpack may not be possible

I have attempted to modify the versions of bootstrap, jquery, and popper without success. I do not believe I am utilizing multiple versions of jquery. I am uncertain as to where the issue may lie. Any assistance in identifying what I may be overlooking wou ...

Tips for generating multiple HTML hyperlinks using a for loop in a Chrome extension

function createDropDown(){ const tree = document.createDocumentFragment(); const link = document.createElement('a'); for(let index = 0; index < urlList.length; index++){ link.appendChild(document.createTextNode(urlList[index])); ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

What is the method to assign a value to ng-class in Angularjs?

I need to categorize items in a list by assigning them classes such as items-count-1, items-count-2, items-count-3, items-count-4, based on the total number of items present. This is how I would like it to appear: li(ng-repeat="area in areas", ng-class=" ...

Guide on displaying the name attribute of a button along with its price in a separate div when clicked

Upon clicking the Koala button, I want to display a message showing the id name of the button and the corresponding price for Koalas. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link h ...

Tips for preventing 404 errors in react-router

I am currently working on a project using React Router and created it using create-react-app. Everything runs smoothly on my local server with links like localhost:3000/login and localhost:3000/product. However, when I deployed the project to my domain, ...

A compilation of audio files compatible with all web browsers, no flash required

Currently in the process of developing a website dedicated to Songs, featuring playlists and mp3 files. I have come across various flash mp3 playlist players, however I am looking to avoid using flash and ensure compatibility with all browsers and smartp ...

Navigating between applications

Does anyone have suggestions on setting up routing between different apps without disrupting existing code? We want to make the integration process easy when adding a new app to our main application. For example, navigating from an electronics(main app) ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

Issues with babel plugin-proposal-decorators failing to meet expectations

I recently included these two devDependencies in my package.json: "@babel/plugin-proposal-class-properties": "^7.1.0", "@babel/plugin-proposal-decorators": "^7.1.6", In the configuration file .babelrc, I have listed them as plugins: { "presets": ["m ...

Is it possible to launch a browser window using javascript?

I need to open a new Internet Explorer browser window and I am currently using the following code: window.open("http://jsc.simfatic-solutions.com", "mywindow"); However, I would like to know how can I open a new IE window with a fresh session? ...