0

I've been messing around with Javascript recently and I'm still a beginner. I've been trying to build a simple program which finds a specified string inside the text entered into the text field using regular expressions, but for some reason when I click the "Find" button it gives me the following error:

Uncaught TypeError: find is not a function
    onclick http://192.168.178.20:62126/JavaScript/Findy/index.html:1
index.html:1:1

Here's my code:

<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Findy</title>
    <link rel="stylesheet" href="style.css">
  </head>

  <body>
    <script src="script.js"></script>
    <form action="">
      <input type="text" id="toFind" placeholder="What do you wanna find?">
      <input type="button" id="find" onclick="find()" value="Find"></input>
      <textarea name="textToSearch" id="textToSearch" cols="30" rows="10" placeholder="Enter your text"></textarea>
    </form>
  </body>

</html>
function find() {
  var text=document.getElementById("textToSearch").value;

  var word=document.getElementById(toFind).value;
  var myRegex=/word/;

  console.log(text.match(myRegex));
}

downmath
  • 147
  • 5
  • 1
    In the scope of the `onclick` attribute, `find` is the button with `id="find"` and not the global `find` variable. `onclick` **attributes** are awful. Use the `addEventListener` method instead. – Quentin Mar 18 '22 at 16:18
  • [The placeholder attribute is not a substitute for the label element](http://www.456bereastreet.com/archive/201204/the_html5_placeholder_attribute_is_not_a_substitute_for_the_label_element/) – Quentin Mar 18 '22 at 16:19
  • @Quentin I think you closed this prematurely. There are some other issues with that code. – Andy Mar 18 '22 at 16:27
  • @Andy — That's the issue the question is about. – Quentin Mar 18 '22 at 16:28
  • OP: https://jsfiddle.net/xev41s23/1/ – Andy Mar 18 '22 at 16:32

1 Answers1

-2

You need to add a <script> tag below where the find() function is called.

Second solution is to add async attribute to <script> tag

  • No. If the problem was that the function defined in the script was not defined at the time the function was called then (a) You'd need to make it available **sooner** and not **later** and (b) the error would be a reference error saying that `find` was not defined (the error says it is defined but is not a function). – Quentin Mar 18 '22 at 16:19