Issue with alert not being triggered in browser when using HTML and JavaScript function

Just starting out with HTML and Javascript!

I'm working on a simple program where users can input a card number, and the browser should indicate whether it is valid (between 13-16 digits) or not.

The website looks great, but I'm not getting an alert when a number is entered, valid or invalid. Any ideas on how to solve this issue?

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Validation Program</title>
  <link type=’text/css’/>
  <script>
    'use strict';
    function checkNumber(cardNum) {
        if (cardNum.length > 16 || cardNum.length < 13) {
            alert(‘This number is not valid.’);
            return false;
        } else {
            alert(‘This number is valid!’);
            return true;
        }
    }
  </script>
</head>

<body onload=“document.cardNum()”>

<h4> Enter Card Number: </h4>
<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>
    <br>
    <input type="submit" value=Submit onclick=“checkNumber(cardNum)”/>
</form>

</body>
</html>

Answer №1

After analyzing your code, I found three key issues that needed fixing: 1- The onload function 'document.cardNum()' was causing your page to crash immediately as there is no such function defined. 2- Some of the quotes in your code were not valid, possibly due to formatting during pasting. It's important to use proper quotation marks (" and ') for consistency. 3- Another issue was with your function where you were checking the length of the HTML element instead of the input value itself, causing it to not work correctly.

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    function getNumber(cardNum) {
        if (cardNum.value.length > 16 || cardNum.value.length < 13) {
            alert("This is not valid.");
            return false;}
        else {
            alert("This is valid.");
            return true;}
    }
  </script>
</head>

<body>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id="cardNum" name="cardNum"/>
    <br>
    <input type="submit" value=Submit onclick = "getNumber(cardNum)"/>
</form>

</body>
</html>

Answer №2

Instead of relying solely on Shubham oli's suggestion, consider incorporating HTML5 validations into your code like this.

<form >
    <input type='text'  id="cardNum"  name="cardNum" required pattern='[0-9]{13,16}'/ >
    <br>
    <input type="submit" value='Submit' >
</form>

Answer №3

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Card Reader Application</title>
    <link type=’text/css’/>

    <script>
      function checkCardNumber() {
        var cardNum = document.getElementById("cardNum").value;
        if (isNaN(cardNum) || cardNum.length < 13 || cardNum.length > 16) {
          alert("Invalid input");
        } else {
          alert("Input is valid");
        }
      }
    </script>
  </head>
  <body>
    <h4>Please Enter Your Credit Card Number:</h4>

    <input type="text" id="cardNum" name="cardNum" />

    <button type="button" onclick="checkCardNumber()">Submit</button>
  </body>
</html>

This represents a straightforward and efficient method to validate credit card numbers.

Answer №4

Three things were corrected in your code: 1- The onload attribute calling a non-existent function document.cardNum() was causing the page to crash immediately and preventing further script execution. 2- Some of the quotes used in the code were not valid; you should use " and ' for proper syntax. 3- In your function, you were passing the reference of the input element and checking the length of an HTML element instead of the input value.

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type='text/css'/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length <= 16 && cardNum.length >= 13) {
            alert('This is valid.');
            return false;
          }
        else {
            alert('This is not valid.');
            return true;
          }
    }
  </script>
</head>

<body>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id='cardNum' name='cardNum'/>
    <br>
    <input type="submit" value='Submit' onclick="getNumber(document.getElementById('cardNum').value)"/>
</form>

</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

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

issue with padding-bottom in Firefox and Internet Explorer 11

JsFiddle CSS body, html { background: violet } * { margin: 0; padding: 0 } .fixed { height: 100%; width: 300px; background: #fff; right: 0; position: absolute; top: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

What is the best way to align a tweet in the middle of

When using Twitter to embed a tweet, the code provided is necessary. An example of this can be seen below: <blockquote class="twitter-tweet"><p>NoSQL space gradually becoming SlowSQL space.</p>&mdash; Big Data Borat (@BigDataBorat) & ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...

What could be causing the Gruntfile to throw an error?

Getting an unexpected error while trying to run grunt $ grunt Loading "Gruntfile.js" tasks...ERROR >> SyntaxError: Unexpected token : Warning: Task "default" not found. Use --force to continue. Execution terminated due to warnings. Here is my ...

How can I centrally align the text(link) vertically in relation to its background image?

After setting the background color, height, and width of a link using CSS, I managed to align the text(link) center horizontally by applying the "text-align: center" property. However, I am facing difficulty in vertically centering it with respect to its ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Initiate an AJAX call with various data formats included

I am currently developing an application that allows users to input values through an interface and send AJAX requests (similar to a REST API). My question pertains to sending data of multiple types in a single request. For example, here is a scenario: F ...

Retrieving form parameters within an EJS template

Hey there! I'm diving into the world of Node.js on my own and hitting a stumbling block that seems simple but is causing me some serious frustration. Despite countless searches on Google, I can't seem to figure it out due to fatigue setting in. I ...

Stuck with the same icon even after a successful AJAX call

I am currently working on implementing a 'add to my list' function in my web app. The goal is to change the color of an icon when a user clicks on it, after sending the necessary data to the server. Despite successfully sending the data to the s ...

I need to know how to use Axios to fetch data from multiple sources at the same time without any risk of the

Trying to initiate multiple axios operations simultaneously to fetch data from various sources at once using a loop leads to the received data getting intermingled and corrupted. Even creating distinct axios instances for each data source doesn't see ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

Tips for incorporating Angular2 into Eclipse using TypeScript

Recently, I delved into the world of Angular 2 and noticed that TypeScript is highly recommended over JavaScript. Intrigued by this recommendation, I decided to make the switch as well. I came across a helpful guide for setting up everything in Eclipse - f ...

What methods can be utilized to ensure that my wistia video player/playlist is responsive on different devices

I need some assistance with making my Wistia player responsive while using a playlist. I want the video player to adjust its size based on the screen size. Here is an example: My current code utilizes their iframe implementation: <div id="wistia_1n649 ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Potential issue with Jhipster: loading of data could be experiencing delays

I've encountered an issue with getting my chart to display properly. I am working on creating a chart using ng2-charts, where I retrieve data from a service and then display it on the chart. The problem arises when the data is not correctly displayed ...

Is there a way to prevent this picture from shifting?

I am currently revamping the content on my work website using Joomla. I have received the old copy and now I need to enhance it. The website in question is 24x7cloud.co.uk. At the bottom of the page, I aim to include an "Accreditation's" section. Howe ...