Home > Software engineering >  Uncaught ReferenceError: Function is not defined using external js file
Uncaught ReferenceError: Function is not defined using external js file

Time:06-17

I have a table of rows with contact details and a call button in every row, which when clicked should call the customer.

I am using onclick on call the function defined in external js file (I know not the best practice and potentially due to outside scope, but I am passing the phone number as well)

I am getting error Uncaught Referenceerror: function is not defined

https://jsfiddle.net/e1z25y3w/3/

<table>
<th>
  <td>#</td>
  <td>Name</td>
  <td>City</td>
  <td>Phone Number</td>
  <td>Call</td>
</th>
<tr>
  <td>1</td>
  <td>John</td>
  <td>Melbourne</td>
  <td> 61123456789</td>
  <td><a role="button" onclick="callPhone(' 61123456789')">Call</a></td>
</tr>
<tr>
  <td>2</td>
  <td>Tanya</td>
  <td>Sydney</td>
  <td> 61987654321</td>
  <td><a role="button" onclick="callPhone(' 61987654321')">Call</a></td>
</tr>

</table>

Jquery 3.4.1 included at the bottom of the page javascript file also included after jquery

$(function () {
  //const phoneNumberInput = document.getElementById("phone-number");

function callPhone(phonenumber) {
alert(here);
      log("calling phone number "   phonenumber.value);
      //e.preventDefault();
      phoneNumberInput = phonenumber;
      makeOutgoingCall();
  }
});

What is the best way to execute this?

CodePudding user response:

because the "callPhone" function isn't in the global scope, so when you to try call it, will give "callPhone is not defined".

So, you need to write it on the global scope.

function callPhone(phonenumber) {
  console.log('running')
}

or store it in variable.

let referanceStore = null
$(function () {
//const phoneNumberInput = document.getElementById("phone-number");

function callPhone(phonenumber) {
  // any code here...
  console.log('running')
}
referanceStore = callPhone

});

and use referancecStore to call your function ex:

referanceStore(' 61987654321')

CodePudding user response:

Can you show a little more of info in the html side?

Where are you declaring the .js Is there any event that loads your js file? it´s loaded before, or after you load the table etc...

  • Related