Uncaught TypeError: Function is not a function

Rob Myrick

I am getting Fib.inputValidate is not a function

I am wanting to run the inputValidate method so that on keyup the input validates both as an integer and as a Fibonacci number:

HTML looks like this:

<form id="fibonacci-form" action="" method="post">
  <input id="fibonacci" type="text" name="fibonacci"/>
</form>

Javascript ES6:

class Fibonacci {

  constructor() {
    const isPerfectSquare = '';
    const isFibonacci = '';
    const isInt = '';
    const inputValidate = '';
    this.isPerfectSquare = isPerfectSquare;
    this.isFibonacci = isFibonacci;
    this.isInt = isInt;
    this.inputValidate = inputValidate;
  } // constructor

  inputValidate(valueParsed, isInt) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    field.addEventListener("keyup", function(e) {
      if (this.isInt(valueParsed) === false && field.value !== '') { 
        alert('Please enter a valid integer.'); 
      } 

      if(this.isFibonacci(valueParsed)) {
        alert(valueParsed + ' is a Fibonacci Number.');  
      } else {
        alert(valueParsed + ' is not a Fibonacci Number.'); 
      }
    });
  }

  isInt(valueParsed) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    return !isNaN(valueParsed) && valueParsed == valueParsed.toFixed();
  }

  isPerfectSquare(valueParsed) { 
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0));
    if (field.value !== '') { 
      return (squaredValue * squaredValue == valueParsed); 
    }
  } 

  isFibonacci(valueParsed) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0)); 
      return this.isPerfectSquare(5 * valueParsed * valueParsed + 4) || this.isPerfectSquare(5 * valueParsed * valueParsed - 4); 
  } 
} // class

let Fib = new Fibonacci();
console.log(Fib.inputValidate());
ibrahim mahrir

The real problem is that the this inside event handlers is not what you think it is. The this inside the event handler will be the (DOM) element that fired the event, not the instance of your class.

Now while you were trying to fix the real problem, you ended up with another problem, which is that you are shadowing the class methods with properties that have as values the empty string ''.

To fix this, just remove the constructor all together as it doesn't do anything, and fix the issue with the this inside the event listener. To do that you have plenty of ways:

  1. Use a variable outside the event listener scope called, for example, that, assign this to it and use that instead of this inside the event listener.

Like so:

var that = this;
field.addEventListener("keyup", function(e) {
    // use 'that' instead of 'this'
    if(that.isInt(valueParsed) ...
});
  1. Use an arrow function because arrow functions use their surrounding this value:

Like so:

// notice the arrow function passed to addEventListener
field.addEventListener("keyup", e => {
    // you can now use 'this' here with no problems
    if(this.isInt(valueParsed) ...
});
  1. bind your event handler to the instance of your class. binding a function will create a new function that always have its this value set to whatever you set it to.

Like so:

field.addEventListener("keyup", function(e) {
    // you can now use 'this' here with no problems
    if(this.isInt(valueParsed) ...
}.bind(this)); // bind the function to its surronding 'this' value so 'this' inside it will be the same as 'this' outside it

Working code: Using an arrow function

class Fibonacci {
  inputValidate(valueParsed, isInt) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    field.addEventListener("keyup", e => {
      if (this.isInt(valueParsed) === false && field.value !== '') {
        alert('Please enter a valid integer.');
      }

      if (this.isFibonacci(valueParsed)) {
        alert(valueParsed + ' is a Fibonacci Number.');
      } else {
        alert(valueParsed + ' is not a Fibonacci Number.');
      }
    });
  }

  isInt(valueParsed) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    return !isNaN(valueParsed) && valueParsed == valueParsed.toFixed();
  }

  isPerfectSquare(valueParsed) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0));
    if (field.value !== '') {
      return (squaredValue * squaredValue == valueParsed);
    }
  }

  isFibonacci(valueParsed) {
    var field = document.getElementById('fibonacci');
    var valueParsed = parseInt(field.value);
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0));
    return this.isPerfectSquare(5 * valueParsed * valueParsed + 4) || this.isPerfectSquare(5 * valueParsed * valueParsed - 4);
  }
} // class

let Fib = new Fibonacci();
<form id="fibonacci-form" action="" method="post">
  <input id="fibonacci" type="text" name="fibonacci" />
</form>

Enhanced working code:

There still are some issues with your code that are related to the functionality rather than errors:

  1. You declare functions as having arguments but you are not using them. For instance, the valueParsed argument is not used at all by even though it is an argument in all functions, instead you are fetching it from the DOM element every time. Use the argument.
  2. The valueParsed (now used as argument) will be initialized inside inputValidate. It should be fetched from within the event listener not from outside it (every time the event fires we should get a new value for valueParsed).
  3. For validation use Number instead of parseInt if you want to exclude float numbers (using parseInt will let float numbers pass validation as it takes only the integer bit from them). Also if validation fail, return to stop further code from executing. It (validation) still not very good though, I'll leave that to you.
  4. Suggestion: You may want to use a button and listen for clicks on it instead of listening for keydown input on the field which is annoying. Create a button, and when the user clicks the button then check if the number they entered in the field is a Fibbonacci one or not. You would only change a line or two of code to achieve that.

class Fibonacci {
  inputValidate() {
    var field = document.getElementById('fibonacci');

    field.addEventListener("keyup", e => {
      var valueParsed = Number(field.value);
      if (this.isInt(valueParsed) === false) {
        alert('Please enter a valid integer.');
        return;
      }

      if (this.isFibonacci(valueParsed)) {
        alert(valueParsed + ' is a Fibonacci Number.');
      } else {
        alert(valueParsed + ' is not a Fibonacci Number.');
      }
    });
  }

  isInt(valueParsed) {
    return !isNaN(valueParsed) && valueParsed == valueParsed.toFixed();
  }

  isPerfectSquare(valueParsed) {
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0));

    return (squaredValue * squaredValue == valueParsed);
  }

  isFibonacci(valueParsed) {
    var squaredValue = parseInt(Math.sqrt(valueParsed).toFixed(0));
    return this.isPerfectSquare(5 * valueParsed * valueParsed + 4) || this.isPerfectSquare(5 * valueParsed * valueParsed - 4);
  }
} // class

let Fib = new Fibonacci();
<form id="fibonacci-form" action="" method="post">
  <input id="fibonacci" type="text" name="fibonacci" />
</form>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Uncaught TypeError: $(...).jsGrid is not a function

Uncaught TypeError: $(…).on is not a function

Uncaught TypeError: $(...).accordion is not a function

Uncaught TypeError: $(...).formSelect is not a function

Uncaught TypeError: $(...).stellar is not a function

Uncaught TypeError: $(...).tooltip is not a function

Uncaught TypeError: $(...).pickadate is not a function

Uncaught TypeError: $(...).ready is not a function

Uncaught TypeError: 'download' is not a function

Uncaught TypeError: $(...).tableDnD is not a function

Javascript: Uncaught TypeError: not a function

Uncaught TypeError: #<Object> is not a function

Uncaught TypeError: $.post is not a function

Uncaught TypeError: map is not a function

Uncaught TypeError: Object (...) is not a function

Uncaught TypeError Object is not a function

Uncaught TypeError: .slideToggle is not a function

Uncaught TypeError: $(...).waterwheelCarousel is not a function

"Uncaught TypeError: $ is not a function" in WordPress

Uncaught TypeError: .unshift is not a function

Uncaught TypeError: dispatch(...).then is not a function

Uncaught TypeError: $(...).selectize is not a function

Uncaught TypeError: $ is not a function on weebly

Uncaught TypeError: getFullYear is not a function

Uncaught TypeError: $(...).draggable is not a function

Uncaught TypeError: a(...).countdown is not a function

Uncaught (in promise) TypeError: $ is not a function

Uncaught TypeError: $(...).lightGallery is not a function

REACT Uncaught TypeError .then is not a function

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive