Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields.

Here is the HTML code for the form:

<form action="sendmail.php" method="post" name="cascader"
 onsubmit="prepareEventHandlers()" id="cascader">   
 <div class="TargetCenter">   <p><strong><span class="asterisk">*</span>Target Center</strong>  </p>
 <label>
   <input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />
   All Countries</label>
  ... (more HTML code) ...
   Switzerland</label>
   
   <!-- More HTML code -->
 </form>

Here is the Javascript code I used for the processTitle textfield:


function prepareEventHandlers() {
    document.getElementById("cascader").onsubmit = function() {
        // prevent form submission without a value in processTitle
        if (document.getElementById("processTitle").value == "") {
            document.getElementById("errorMessage").innerHTML = "Please enter a value";
            window.scrollTo(0, 0);
            document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
            return false;
        } else {
            document.getElementById("errorMessage").innerHTML = "";
            return true;
        }
    };
}

window.onload = function() {
    prepareEventHandlers();
};

function checkFieldValue() {
    if (document.getElementById("processTitle").value != "") {
        document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
        document.getElementById("errorMessage").innerHTML = "";
    } else {
        document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
    }
}

Answer №1

I have implemented a small function to verify if any radio button is selected. You can find the checkRequiredRadioButtons function at the end of the JavaScript code below. Currently, I have linked it to your existing validation failure code.

function prepareEventHandlers() {
        document.getElementById("cascader").onsubmit = function() {
          // prevent a form from submitting if no email.
          if (document.getElementById("processTitle").value == "" || !checkRequiredRadioButtons('cascadeType')) {
            document.getElementById("errorMessage").innerHTML = "Please enter a value";
            // to STOP the form from submitting
            window.scrollTo(0, 0);
            document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
            // to turn the field background color
            return false;
          } else {
            // reset and allow the form to submit
            document.getElementById("errorMessage").innerHTML = "";
            return true;
          }
        };
      }
      // when the document loads
    window.onload = function() {
      prepareEventHandlers();
    };
     // Changes the field color onFocus
    function checkFieldValue() {
      if (document.getElementById("processTitle").value != "") {
        document.getElementById('processTitle').style.cssText = 'background-color: #FFF;';
        document.getElementById("errorMessage").innerHTML = "";
      } else document.getElementById('processTitle').style.cssText = 'background-color: #f4fc99;';
    }

    function checkRequiredRadioButtons(buttonsName) {
      var buttonSet = document.getElementsByName(buttonsName);

      for(i = 0; i < buttonSet.length; i++){
          if(buttonSet[i].checked == true)
            return true;
      }
      return false;
    }
<form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader">
  <div class="TargetCenter">
    <p><strong><span class="asterisk">*</span>Target Center</strong> 
    </p>
    <label>
      <input type="checkbox" name="TargetCountry" value="allCountries" id="TargetCountry" />All Countries</label>
    <label>
      <input type="checkbox" name="TargetCountry" value="France" id="TargetCountry" />France
    </label>

    ... (Other checkbox inputs) ...

    <br />
  </div>
  <!--end of Cascade Target-->
  ... (Other parts of the form) ...
</form>

If you want to dynamically determine whether you are dealing with a textbox or a radio button, you can use Element.getAttribute('type') and compare as shown in the code snippet below:

var allInputs = document.getElementsByTagName('input');
for(i = 0; i < allInputs.length; i++){
    if(allInputs[i].getAttribute('type') == 'radio'){
        // Do radio button handling
    } else if(allInputs[i].getAttribute('type') == 'text'){
        // Do textbox handling  
    }
}

Keep in mind that with this approach, you will iterate through all radio buttons in the group, checked and unchecked, as well as other input types like submit and reset buttons.

Answer №2

Have you considered using the javascript getElementsByTagName() method? It could be helpful:

function validateFields() {
 var elements = document.getElementsByTagName("input");
 for (var i=0; i<elements.length; i++){
  if(elements[i].value==""){
   elements[i].style.backgroundColor="red";
  }
 }

}

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

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

How do I set up a slideshow to loop continuously?

I created a slideshow for my website using the script below, but I'm struggling to figure out how to make it repeat. I want the slideshow to go back to the first photo after reaching the last one. Can anyone help please? For reference, please check o ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...

I'm having trouble with successfully multiplying arrays in Java

I'm facing an issue with my code - the weightedProduct() method only returns 0.00. Can anyone pinpoint where I made a mistake? The goal is to calculate the product by multiplying units * price and then return the resulting product. public class Fram ...

Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method? https://i.sstatic.net/xo56M.png .d-flex { display: flex; } .d-fl ...

Eliminating certain buttons within Ember-leaflet-draw

Is there a way to remove specific buttons from the UI in my Ember application that are used for drawing lines, circles, and polygons? I am currently using Leaflet Draw in my project. Here is a snippet of my template.hbs: {{#leaflet-map onLoad=(action &apo ...

Understanding the index_key parameter in the PHP array_column function

Currently, I am utilizing the PHP function $array = [ 'red' => ['nice' => true, 'hot' => true], 'green => ['nice' => true, 'hot' => false ] array array_column ( array $array , mixe ...

What sets apart "React.useState setter" from "this.setState" when updating state?

After clicking on the button in AppFunctional, the component fails to update even though the state has changed. However, everything works fine in AppClass. In both cases, we are mutating the original state with "push", but I'm struggling to understan ...

"Enjoying the convenience of a stationary header while browsing on your smartphone

Hey there! I'm currently facing an issue with my website's fixed horizontal nav bar when zooming in on a mobile device. After doing some research, it seems the only solution is to implement some javascript. I came across a jquery fix (see below) ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...

NodeJs and Mysql query execution experiencing significant delays

NodeJs + Mysql query delays and execution timing issue https://github.com/mysqljs/mysql Hello everyone, I'm facing a problem with mysql js. Whenever I use .query(), the callback is taking too long to execute and returning empty results. However, if I ...

Issue with ng-grid in AngularJS: Data does not appear after resizing columns

Currently, I am encountering a problem where ng-grid data is not being displayed when column resizing occurs after changing the column names. To demonstrate this issue, I have created a plunkr at - http://plnkr.co/edit/eV9baoDOV9A46FZmKW8G?p=preview I wo ...

Tips for overlaying an image on a div regardless of its height

(!) Although this question may seem repetitive, I have not been able to find a suitable solution in any of the previous 10 topics. I apologize for the inconvenience and am actively seeking a resolution to this unique situation; Allow me to outline the iss ...

Struggling to properly line up the baselines of navigation list items that are styled as circular elements using CSS

I have transformed my navigation menu into a series of CSS circles with text inside. The issue I am facing is that the text spills out unevenly based on the amount of content in each circle. To address this, I used a JavaScript solution to center-align the ...

What is the best way to apply attributes to all titles throughout a webpage?

My goal is to locate all elements on the page that have a title attribute and add a new attribute to each of them. For example: <div title='something 1'></div> <p>Test<div title='something 2'></div></p ...

Global asynchronous functionality can be enabled in JavaScript

Wouldn't it be convenient to have the option to enable async functionality in the global scope? This way, there would be no need to wrap all asynchronous operations within a function. I'm curious if this is achievable in browser JavaScript or per ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

How can I delete the onmouseover function in HTML?

Is there a way to remove the (onmouseover="mouseoversound.playclip()") function from the following HTML code? <a href="roster.html" onmouseover="mouseoversound.playclip()">Roster</a> Can we instead implement this functionality in a JavaScript ...

What benefits does utilizing Microsoft Workflow Foundations offer?

I am currently working with an investor who is pushing for us to utilize Microsoft Work Flow Foundations for our workflow and database. However, I have already created an interactive graph-database using Javascript, Node.Js, and ArangoDB that perfectly su ...

What is preventing the direct passing of the dispatch function from a useState hook into an onClick handler function?

const Counter = () => { const [count, setCount] = useState(0); // Uncommenting the line below would result in an infinite loop because it directly invokes setCount(count + 1) on render. // This causes the component to continuously re-render and up ...