Search code examples
javascripthtmlfunctionreturnalert

Function not sending alert in browser HTML, JavaScript


Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

<!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 not valid.’);
            return false;}
        else {
            alert(‘This is valid.’);
            return true;}
    }
  </script>
</head>

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

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

Solution

  • There was 3 things i fixed; 1- onload=“document.cardNum()” , there is no function like that so your page crashes immediately so no further script executes 2- I dont know if it is spoilt during paste but some of your quotes are not valid, you should use " and ' 3- This one just prevents working right; In your function you pass input's reference and check HTML element's length you need to check input's 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>
        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>