wyc
wyc

Reputation: 55353

Why is my onclick event throwing undefined?

I have the following button:

<input type="button" onclick="printDiv('print-content')" value="print a div!"/>

And the following JavaScript right below:

<script>
$(function() {
  function printDiv(divName) {
   alert('s')
     var printContents = document.getElementById(divName).innerHTML
     w=window.open()
     w.document.write(printContents)
     w.print()
     w.close()
  }
})
</script>

When I click printDiv, though I get the following error:

Uncaught ReferenceError: printDiv is not defined payment-history:398 onclick

I really don't get it.

Upvotes: 3

Views: 3845

Answers (1)

Vigneswaran Marimuthu
Vigneswaran Marimuthu

Reputation: 2532

Because printDiv is not in global scope. You have wrapped it with a function. So, printDiv scope is within that immediate function and not global.

JavaScript scoping and Hoisting

Upvotes: 6

Related Questions