func is not defined at HTMLButtonElement.onclick

Issue

I’m trying to create a simple webpage using Flask, I’m trying to capture the text written in a textfield in a javascript variable and then display it on console, when the user presses a button.

Here is the code

HTML

<script type="text/javascript" language="javascript" src="{{url_for('static',filename='js/main.js')}}"></script>

<div class="container">
    <div class="row">
      <div class="col-md-3"></div>
      <div class="col-md-6">
        <input type="text" id="txtWord" name="search" placeholder="Search..." >
      </div>
      <div class="col-md-3"></div>
    </div>

    <div class="row">
      <div class="col-md-3"></div>
      <div class="col-md-6">
        <input type="text" name="search" placeholder="# Result..." id="inputNumResults">
      </div>
      <div class="col-md-3"></div>
    </div>

    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-4 text-center">
        <br>
        <button class="btn btn-success" type="button" id="buttonSearch" onclick="getText()">Search for words</button>
      </div>
      <div class="col-md-4"></div>
    </div>

Javascript

function getText() {
    var txt = document.getElementById('txtWord').innerHTML;
    console.log(txt);
}

Solution

Here is working solution

<div class="row">
  <div class="col-md-3"></div>
  <div class="col-md-6">
    <input type="text" id="txtWord" name="search" placeholder="Search..." >
  </div>
  <div class="col-md-3"></div>
</div>

<div class="row">
  <div class="col-md-3"></div>
  <div class="col-md-6">
    <input type="text" name="search" placeholder="# Result..." id="inputNumResults">
  </div>
  <div class="col-md-3"></div>
</div>

<div class="row">
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center">
    <br>
    <button class="btn btn-success" type="button" id="buttonSearch" onclick="gt()">Search for words</button>
  </div>
  <div class="col-md-4"></div>
</div>

<script>
    function gt() {
        var txt = document.getElementById("txtWord").value;
        alert(txt);
    }
</script>

https://jsfiddle.net/ovtkmnmn/3/

I believe in Your case the problem is about order of loading this js file.

Always check what console displays, when I used “On load” load type it clearly returned an error that the function is not defined

Answered By – Tomasz Grochowski

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.