Struggling with incorporating validation using JavaScript in HTML

As a newcomer to the world of html and js, I am struggling to incorporate js into my html code. Despite multiple attempts at modification, I have not been successful in getting it to work. Any guidance or advice on this issue would be highly appreciated.

I have experimented with various elements such as input types, actions, if and else if statements, alert functions, and much more.

function validation() {
  var name = document.getElementById('Name').value;
  var email = document.getElementById('Email').value;
  var tel = document.getElementById('Telephone').value;
  if (Name == '' || Email == '' || Telephone == '')
    alert('action required')
  return false;
} else if (name.length < 4) {
  alert("action required")
  return false;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="utf-8">
  <link rel="stylesheet" href="css/WebForm.css">
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>COM111 | WebForm | B0076234</title>
  <meta name="viewport" content="width = device-width, inital-scale = 1.0">
  <script src="assignment2/ass2script.js"></script>
  <h1 id="h1">Welcome To My WebForm</h1>
  <h2 id="h2"> CV Request</h2>
</head>

<body>
  <!-- form -->
  <form action="" method="post" onsubmit="return validation()">
    <div class="wrap">
      <div class="form1">
        <div class="input-fields">
          <input type="text" class="input" placeholder="Name" id="name">
          <input type="email" class="input" placeholder="Email" id="Email">
          <input type="tel" class="input" placeholder="Telephone" id="Telephone">
          <input type="text" class="input" placeholder="Company" id="Telephone"><br>
          <input type="submit" name="submit" value="Insert now">
          <label>Short CV
            <input type="radio" checked="checked">
          </label> <br>
          <label>Long CV
            <input type="radio">
          </label>
        </div>
        <div class="message">
          <textarea placeholder="Message"></textarea>
          <div class="btn">send</div>
        </div>
      </div>
    </div>
  </form>

  <div id="eresult"></div>
  
</body>

</html>

Answer №1

Resolve the following issues:

  1. Ensure braces are added around the block after if because it contains multiple statements. For more information, refer to: Why is it considered a bad practice to omit curly braces?
  2. Add an additional brace at the end of the function.
  3. Modify id="name" to id="Name" to match the call to document.getElementById('Name').
  4. Correct the variable names in the initial if statement to align with the variables assigned from the input values.

All of these validations can actually be integrated into the HTML itself. You can utilize the required attribute for inputs that must be completed and apply minlength="4" on the Name input to mandate a minimum character length of 4.

function validation() {
  var name = document.getElementById('Name').value;
  var email = document.getElementById('Email').value;
  var tel = document.getElementById('Telephone').value;
  if (name == '' || email == '' || tel == '') {
    alert('action required')
    return false;
  } else if (name.length < 4) {
    alert("action required")
    return false;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="utf-8">
  <link rel="stylesheet" href="css/WebForm.css">
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>COM111 | WebForm | B0076234</title>
  <meta name="viewport" content="width = device-width, inital-scale = 1.0">
  <script src="assignment2/ass2script.js"></script>
  <h1 id="h1">Welcome To My WebForm</h1>
  <h2 id="h2"> CV Request</h2>
</head>

<body>
  <!-- form -->
  <form action="" method="post" onsubmit="return validation()">
    <div class="wrap">
      <div class="form1">
        <div class="input-fields">
          <input type="text" class="input" placeholder="Name" id="Name">
          <input type="email" class="input" placeholder="Email" id="Email">
          <input type="tel" class="input" placeholder="Telephone" id="Telephone">
          <input type="text" class="input" placeholder="Company" id="Telephone"><br>
          <input type="submit" name="submit" value="Insert now">
          <!--buttons-->
          <label>Short CV
<input type="radio" checked="checked">
    </label> <br>
          <label>Long CV
     <input type="radio">
    </label>
          <!-- messgebox -->
        </div>
        <div class="message">
          <textarea placeholder="Message"></textarea>
          <div class="btn">send</div>
        </div>
      </div>
    </div>
  </form>
  <!--buttons-->
  <div id="eresult"></div>
  <!-- javascript -->
  <script type="text/javascript">
  </script>

</body>

</html>

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

Closing Note in Drupal

Is there a way to adjust the footer message in Drupal without logging into the dashboard? I've checked all the files in cPanel, but I can't seem to locate the actual HTML for the website. I am only able to customize the body content, not the fo ...

Experiencing difficulty connecting to WebSocket while running the app on Heroku (Node.js) platform

After attempting to deploy my web application utilizing Websockets on Heroku, I found that I am unable to connect to the designated listening port. //Server const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8000 }); app.u ...

Inline-block elements are cascading downwards following the initial sibling div

I have encountered an issue that I am struggling to identify the root cause of. Initially, I had three boxes aligned in a horizontal line as intended. However, upon adding titles and descriptions inside the boxes, they now appear staggered. What could be c ...

What are some tips for using CSS display grid to effectively showcase my HTML content?

Visit my About Me page with custom menu styling Any tips on aligning the body with the grid function to achieve this particular design? ...

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

Using conditional statements with a series of deferred actions in jQuery

In the scenario where I have chained the $.Deferred as shown below: $.each(data, function(k, v) { promise.then(function() { return $.post(...); }).then(function(data) { if(data)... // here is the conditions return $.post(.. ...

Customize jQuery Autocomplete choices depending on another jQuery Autocomplete input

I need to implement a feature where users can select a company and then an employee from that company. I came across a similar question on this link, but I specifically want both inputs to be autocomplete-enabled. This is the code snippet I currently have ...

Restricting the amount of requests per user within a single hour [Node.js]

As I work on developing a server side application using Nodejs and Express, one thing that crosses my mind is limiting the number of requests per user within a specific time frame to prevent malicious hackers from overwhelming the server with spam. I&apos ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

A step-by-step guide on showcasing three post images in separate divs at the bottom of a webpage with Reactjs and Css

In the array below, there are three post photos. When I click on each post button, I should see a corresponding post photo div at the bottom for each post. Issue: I am facing a problem where only one post photo div is being displayed, which keeps replaci ...

What is the best way to apply the setInterval method to individual custom control objects?

In my project, I developed a custom control and instantiated two objects of it in SAPUI5. Within the onAfterRendering function of my customControl.js file, I implemented a setInterval code to periodically update the value property of the custom control. Th ...

What is the best way to apply typography theme defaults to standard tags using Material-UI?

After reading the documentation on https://material-ui.com/style/typography/ and loading the Roboto font, I expected a simple component like this: const theme = createMuiTheme(); const App = () => { return ( <MuiThemeProvider theme={theme}> ...

Issue with the createActionThunk feature in redux toolkit

Hey there, I'm having an issue with my createAsyncThunk function. It seems to be working fine in manipulating the state by removing a value with a specific index, but for some reason, it's not updating the Firebase database. Also, when I try to a ...

Best practices for loading and invoking Javascript in WordPress child themes

After spending countless hours searching for a detailed tutorial on how to properly incorporate Javascript into a WordPress website, I came up empty-handed. Running the Genesis Framework with a child theme on my localhost, I am eager to add a fullscreen b ...

Struggling to Retrieve Specific Keys for Individual Values in Firebase with React Native

I am currently experiencing difficulty obtaining a unique key for each value in the 'users1' table. firebase.database().ref('users1').once('value').then(snapshot => { var items = []; snapshot.forEach((child) => { ...

Node.js file successfully establishes a database connection, but script tags fail to do so

Having some trouble connecting to my MongoDB database (or MongoLab server). It works perfectly fine when the code is in the name.js file, but for some reason it fails when placed inside <script> tags within an HTML file. My folder contains only thes ...

ReactJS library encounters "Failed to load PDF file." error intermittently while attempting to view a PDF file

I recently developed a React JS application using create-react-app and decided to incorporate react-pdf for viewing PDF files. However, I've encountered an intermittent issue where the PDF sometimes fails to load. Specifically, when I initially load t ...

Allocating memory for JavaScript data types

In my quest to maximize the efficiency of a mobile app I am currently developing, I am curious to find out which data types consume the least amount of memory (keeping in mind that this could differ depending on the browser): object pointers boolean lite ...

Fetching Data Using Asynchronous API Calls

My goal is to retrieve all results consistently from the API, but I am encountering varying outcomes. The for loop seems to be skipping some requests and returning a random number of records. Can anyone provide assistance? I have experimented with using t ...