Having trouble getting JavaScript validation to function properly

I'm struggling to make validation work properly when hitting the submit button. No alert messages appear, even though I should be receiving alerts for empty fields. Can someone identify what is wrong with my code? I have tried checking the validation line by line, but still can't figure out the issue.

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  var y = document.forms["myForm"]["comment"].value;
  if (x == "" && y == "") {
    alert("Please fill out all required fields!");
return false;
   } else if (x == "") {
    alert("Please enter your name!");
    return false;
   } else if (y == "") {
    alert("Please leave us a comment!");
    return false;
   } else {
   if(document.getElementById('r5').checked) {
      window.alert("Thank you")
      }
   }
}
.wrapper {
  display: inline-block;
}

.wrapper * {
  float: right;
}

.wrapper input {
  display: none;
}

label {
  font-size: 30px;
}

input:checked ~ label {
  color: red;
}
<!doctype html>
<html>

<link REL="StyleSheet"  TYPE="text/css" HREF="example2.css">

<body>

  <form id ="myForm">
    Name: <input type="text" id="fname">
    <br><br>
    Comment: <input type="input" id="comment">
    <br><br>



    <div class="wrapper">
      <input type="radio" id="r1" name="rg1">
      <label for="r1">&#10038;</label>
      <input type="radio" id="r2" name="rg1">
      <label for="r2">&#10038;</label>
      <input type="radio" id="r3" name="rg1">
      <label for="r3">&#10038;</label>
      <input type="radio" id="r4" name="rg1">
      <label for="r4">&#10038;</label>
      <input type="radio" id="r5" name="rg1">
      <label for="r5">&#10038;</label>
    </div>
<br>

<button type="button" value="Submit" onclick="validateForm"()>Submit </button>
  </form>
  
</body>
<script src="jsreview.js"></script>
</html>

Appreciate your assistance with this matter.

Answer №1

Assign an identifier to your form and submission button as illustrated.

<form id="myForm">
<input type="submit" value="Submit" id="submit">

In addition, include the following line in your JavaScript file.

document.getElementById('submit').addEventListener('click', validateForm); 

Answer №2

Make sure you are not linking submit functions with javascript functions. Sometimes the submit button defaults to form submission, so consider using a button type instead of submit.

For debugging purposes, set an alert() in the first line of your function to easily check it.

<input type="button" value="SUBMIT" onclick="validateform()" >

or

<button onclick="myFunction()">Click me</button>

<script> function myFunction() {  alert("Hello World"); } </script>

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

Having trouble adjusting the refresh timer based on user focus with setTimeout

For the past few days, I've been utilizing an ajax call to dynamically refresh specific elements of my webapp every 5 seconds. The implementation with setInterval(refreshElements, 5000) worked perfectly fine. However, now I am considering whether the ...

Access a webpage in an html document using URL variables

In the process of developing an MVC web app without utilizing any MVC framework, I have created an index.html file with a section that dynamically loads all the views as needed by the user. However, I encountered an issue where direct URLs such as www.foo. ...

issues with jquery functionality on user control page

For searching through dropdown lists in my project, I have implemented the Chosen jQuery plugin. In the Master page before the closing body tag, ensure to include the necessary CSS and jQuery script files. <link href="/assets/css/chosen.css" rel=" ...

Cross-origin resource sharing (CORS) allows for the secure transfer of data across different

Currently, I am faced with a challenge in making an XmlHTTPRequest POST request from a page loaded via HTTPS to a different domain using an HTTP URL. The HTTP server in question is local and does not support HTTPS due to being within a home setup (like a s ...

How to selectively display specific columns when outputting JSON to a dynamic HTML table?

I'm looking to output specific JSON data in an HTML table with JavaScript. The headers will remain the same, but the JSON content will vary. Currently, I have a working function that generates the entire table using JavaScript: <body> ...

Having trouble creating a text channel in discord.js

Today I successfully programmed a bot to respond to the "!new" command, but encountered an unexpected issue. The current functionality of the bot creates a channel named "support-1" when prompted with the "!new" command. However, every subsequent use of th ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

An error was thrown: SyntaxError - { was not expected in script.js on line 5 while checking request

I encountered an issue while executing the code snippet below: var req = new XMLHttpRequest(); req.open('GET', 'data.json'); req.onreadystatechange = function() { if ((req.readyState === 4) && (req.status == 200)) { var cus ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

Tips for keeping the DropDown Menu displayed even after moving the cursor away from the targeted element in Material-UI

import React from 'react'; import { makeStyles, Typography, Grid } from '@material-ui/core'; const styles = makeStyles((theme) => ({ root: {}, textStyle: { fontFamily: 'brandon-grotesque-black', tex ...

Eliminate repetitive elements within an array of objects

Is there a way to eliminate duplicate values in an object array using Javascript? 0: {d: “2021/01/19”, color: “#009988"} 1: {d: “2021/01/19”, color: “#CC3311"} 2: {d: “2021/01/19”, color: “#009988"} 3: {d: “2021/01/19”, ...

Styling components in React using inline styles that are based on JSON values

I'm successfully pulling in JSON data and mapping it within a React component. However, one of the values in the JSON is a HEX code that I want to apply as an inline style for the background color of a div. I have experimented with various methods, b ...

Implement a "View All" link to toggle between displaying all items and keeping one item open by default,

I am working on multiple toggles for each letter of the alphabet. To make it easier for users, I want to add a "See All" button that will open any closed toggles. Additionally, I want the toggle for the letter A (div1) to be automatically open when the pag ...

What could be causing the malfunction of Bootstrap Multiselect functionality?

I have been attempting to set up Bootstrap Multiselect but it simply refuses to work. Despite trying various solutions, I am unable to pinpoint the issue. My index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF- ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Error encountered with jQuery XML: 'Access-Control-Allow-Origin' header is not present on the requested resource

For a personal project I'm working on just for fun, I'm trying to read an XML file from , parse the data, and use it to convert currency values. Although my code to read the XML is quite basic, I encountered the following error: XMLHttpRequest ...

Arrangement featuring two distinct types of tiles

Looking for a way to achieve this layout using just CSS or a combination of CSS and a little JS. Click on my avatar to see the reference image enlarged =) I've tried using floats and display options but haven't been successful. Take a look at htt ...

JavaScript's Math.round function does not always produce accurate results

After adding the specified line within the function, the code seems to encounter issues. parseLocalFloatCnt: num = Math.round(num*1.2); Is there a solution available for this problem? Your help is much appreciated. <!DOCTYPE html> <html> < ...

The process of redirecting a web page using htaccess and incorporating URL parameters

I have a directory where I store HTML pages. Using the PHP include function, I am adding these pages to my index.php file by referencing them with a URL parameter value. The URL parameter "xpage" corresponds to the page names stored in another folder, whil ...

Using JQuery to eliminate Javascript code after setting up an event listener, but prior to the listener being activated

Having trouble finding a solution to my question through search. I'm sorry if it has already been asked before. I am attempting to define an event listener and immediately remove the JS code after defining it. The challenge is that I want the removal ...