patrick
patrick

Reputation: 16999

button element onclick to run javascript function without JQuery

Why won't this give an alert? I need to make it work without JQuery and with the "button" element since the button is being auto-generated. It works if I put the javascript inside the quotes, but I want to call a function.

<button onclick='test()' >click</button>

javascript

function test()
{
alert('hi');
}

https://jsfiddle.net/nn90okdj/1/

Upvotes: 1

Views: 1004

Answers (4)

kukkuz
kukkuz

Reputation: 42370

The function test does not work in the jsFiddle environment because what you write in the javascript section is placed into the window.onload handler by jsFiddle.

If you do not want to change any settings, directly add to the global scope like here: https://jsfiddle.net/93a8rtaf/

this.test = function () {
  alert('hi');
}
<button onclick='test()' >click</button>

Upvotes: 0

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

Your function is not working correctly because, script is getting loaded at top of the html page. It should be loaded at the bottom if you want to access the DOM element

  • Click on the Javascript button
  • Select No wrap in body
  • It should work properly now

To rectify this.

Javascript Configuration

Upvotes: 0

Christopher Messer
Christopher Messer

Reputation: 2090

Fiddle is being weird. Your code is fine.

https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onclick

Upvotes: 1

The_Outsider
The_Outsider

Reputation: 1925

Seems to work right for me here.

function test()
{
alert('hi');
}
<button onclick='test()' >click</button>

Upvotes: 0

Related Questions