JavaScript button onclick not working - javascript

<button onclick="hello()">Hello</button>
<script>
function hello() {
alert('Hello');
}
</script>
This is my code. But it's not working. When I click on the button nothing happens.

Note to other developers coming across this, you can run into this if you use a reserved method names e.g. clear.
<!DOCTYPE html>
<html>
<body>
<button onclick="clear()">Clear</button>
<button onclick="clear2()">Clear2</button>
<script>
function clear() {
alert('clear');
}
function clear2() {
alert('clear2');
}
</script>
</body>
</html>

How about this?
<button id="hellobutton">Hello</button>
<script>
function hello() {
alert('Hello');
}
document.getElementById("hellobutton").addEventListener("click", hello);
</script>
P.S. You should place hello() above of the button.

Ran into this problem myself so I can confirm something's not right. The difference is that I am generating the DOm Element at runtime. Replacing onclick with onmousedown seemed to do the trick if you can't find a place to addEventListener in your code.

I had a similar issue. I had child.js and a common.js files. In my case, My HTML file was using both the JS files and both of them had a function with the same name,
child.js
function hello(){}
and also
common.js
function hello(){}
After I remove one of these my code works fine and onclick started working. hope this helps!

using onclick vs EventListeners.
The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.
jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:
$(element).on('click', function () { /* do stuff */ });
Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
// example
~```
addEvent(
document.getElementById('myElement'),
'click',
function () { alert('hi!'); }
);
Try it: http://jsfiddle.net/bmArj/
Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.

There is no problem with your code.. run this snippet
function hello() {
alert('Hello');
}
<button onclick="hello();">Hello</button>
and if you want to alert this on window load. change your code like this way
(function(){
alert('hello')
})();

Add:
type="button"
to the button element. The default type is "submit" which is submitting the form before the script is run.

In my case there are was two same elements with position: absolute. I set onclick on the first one so it haven't been called because second element was covering it

I had the same issue, for me, it did not work because of my main.js having type="module", if you don't need type="module" this will work.
<body>
<button onclick="onBtSave()">Save filter model script type module</button>
<button onclick="onBtRestore()">Restore filter model no script type</button>
<script type="module">
// broken
function onBtSave() {
console.log("saving current filter model");
}
</script>
<script >
// working
function onBtRestore() {
console.log("restoring current filter model");
}
</script>

This happened to me when I opened another folder in visual studio code. I just opened new window of visual studio code and only opened one folder this time and it now works

I had the same problem and that's because of reserved method names. We just change the function name.
function click() {
alert('hi')
}
function click1234() {
alert('hi')
}
<body>
<button onclick="click()">login</button>
<button onclick="click1234()">login1234</button>
</body>

For other devs with more advanced code, sometimes an absolute position element is blocking the button. Make sure no element is blocking the button(s) from being clicked.

Write a semicolon after hello function like this
<button onclick="hello();">Hello</button>

Related

How to run a function on a page with Capybara/Poltergeist?

I have a page with JS functions (which are called on mouse click) within <script> ... </script> tags. While I was testing I had encountered problems with .click method not working many times. Therefore I decided to simply call that function manually. However I found no source on the Internet which taught to do this.
I want to avoid clicking the links and simply call for doSumbit('5').
Thank you!
The JS functions are:
<script language="javascript">
function doSubmit(infoTypeId) {
document.forms[1].INFOTYPEID.value = infoTypeId;
document.forms[1].action = document.forms[1].action + "#" + infoTypeId;
document.forms[1].submit();
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
function doSubmitOne(infoTypeId) {
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
</script>
and the on-click links are:
<a href="javascript:doSubmit('11')" >Engine News<br></A>
<a href="javascript:doSubmit('5')" >Parts Identification<br></A>
You can run arbitrary JS with execute_script
page.execute_script("doSubmit('5')")
if you expect a return value use evaluate_script - it's all documented here - http://www.rubydoc.info/gems/capybara/Capybara/Session#evaluate_script-instance_method
Of course if you're actually testing an app, you'd be much better off figuring out why click isn't working for you and fixing that, since by just calling JS functions you're not actually testing that your app works.
EDIT: typo doSubit changed to doSubmit

Javascript document.ready in multiple files with Gulp [duplicate]

If I have a lot of functions on startup do they all have to be under one single:
$(document).ready(function() {
or can I have multiple such statements?
You can have multiple ones, but it's not always the neatest thing to do. Try not to overuse them, as it will seriously affect readability. Other than that , it's perfectly legal. See the below:
http://www.learningjquery.com/2006/09/multiple-document-ready
Try this out:
$(document).ready(function() {
alert('Hello Tom!');
});
$(document).ready(function() {
alert('Hello Jeff!');
});
$(document).ready(function() {
alert('Hello Dexter!');
});
You'll find that it's equivalent to this, note the order of execution:
$(document).ready(function() {
alert('Hello Tom!');
alert('Hello Jeff!');
alert('Hello Dexter!');
});
It's also worth noting that a function defined within one $(document).ready block cannot be called from another $(document).ready block, I just ran this test:
$(document).ready(function() {
alert('hello1');
function saySomething() {
alert('something');
}
saySomething();
});
$(document).ready(function() {
alert('hello2');
saySomething();
});
output was:
hello1
something
hello2
You can use multiple. But you can also use multiple functions inside one document.ready as well:
$(document).ready(function() {
// Jquery
$('.hide').hide();
$('.test').each(function() {
$(this).fadeIn();
});
// Reqular JS
function test(word) {
alert(word);
}
test('hello!');
});
Yes you can easily have multiple blocks. Just be careful with dependencies between them as the evaluation order might not be what you expect.
Yes it is possible to have multiple $(document).ready() calls. However, I don't think you can know in which way they will be executed. (source)
Yes it is possible but you can better use a div #mydiv and use both
$(document).ready(function(){});
//and
$("#mydiv").ready(function(){});
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject).
That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Check this fiddle for working version
Yes you can.
Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.
Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.
Yes, it's perfectly ok.but avoid doing it without a reason. For example I used it to declare global site rules seperately than indivual pages when my javascript files were generated dynamically but if you just keep doing it over and over it will make it hard to read.
Also you can not access some methods from another
jQuery(function(){}); call
so that's another reason you don't wanna do that.
With the old window.onload though you will replace the old one every time you specified a function.
It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
You can also do it the following way:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("#test").hide();
});
$("#show").click(function(){
$("#test").show();
});
});
</script>
</head>
<body>
<h2>This is a test of jQuery!</h2>
<p id="test">This is a hidden paragraph.</p>
<button id="hide">Click me to hide</button>
<button id="show">Click me to show</button>
</body>
the previous answers showed using multiple named functions inside a single .ready block, or a single unnamed function in the .ready block, with another named function outside the .ready block. I found this question while researching if there was a way to have multiple unnamed functions inside the .ready block - I could not get the syntax correct. I finally figured it out, and hoped that by posting my test code I would help others looking for the answer to the same question I had

Issue with assigning onClick to link tag <a>

Iam trying to assign a javascript function to a html link tag using this.
link
But what happens is the function doSomething is executed when I click the link second time. Nothing happens on the first click.
Anyone has any idea about this?
Modify your doSomething() function so that it does not cause the problem. (The problem does not occur if the function e.g. displays some text.) To get more specific help, you need to disclose more information.
Seperate your JavaScript from your HTML by using .addEventListener,
link
document.getElementById('myLink').addEventListener('click', doSomething, true);
and in doSomething remember to use event.preventDefault() to stop the click from performing an action.
In my computer it works with the first click.
<html>
<head>
<script type="text/javascript">
function doSomething() {
alert("Hi :)");
}
</script>
</head>
<body>
Click
</body>
</html>
Using Firefox.
Anyway, why use the href="javascript:;" then?
Actually the doSomething() function here creates a MooTools dialog. Here is the code for that
function doSomething(tit,text,id) {
new mBox.Modal({
content: unescape(text),
setStyles: {content: {padding: '25px 15px', lineHeight: 25, height:'400px'}},
title: unescape(tit),
attach: id
});
}
May be this is what is causing the problem. But not really sure.

jQuery ready firing before custom behavior script initializes

Background
I've inherited an ancient web application that has input controls with custom behaviors defined with an old-fashioned HTC (HTML Component) script, e.g.:
<input name="txtFiscalYearEndDay" type="text" value="30"
maxlength="2" size="5" id="txtFiscalYearEndDay" class="Text1"
style="behavior:url(/path/js/InFocus.htc);" />
Here are the relevant parts of this HTC file to illustrate the issue:
<PUBLIC:COMPONENT tagName="InFocus">
<PUBLIC:METHOD NAME="setValid" />
<PUBLIC:ATTACH EVENT="ondocumentready" HANDLER="initialize" />
<SCRIPT LANGUAGE="javascript">
function initialize() {
// attaches events and adds CSS classes, nothing fancy
}
function setValid(bInternal) {
// checks some flags and changes a label
}
</SCRIPT>
</PUBLIC:COMPONENT>
So, nothing out of the ordinary so far. Additionally, I have some JS that runs on DOM-ready:
$(function() {
txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
});
And the validation function:
function txtFiscalYearEndDay_Validate(el) {
...
}
Note: I'm not using $('#txtFiscalYearEndDay') because then I really can't try to call setValid(true); on the element, nor do I want to have to do $('#txtFiscalYearEndDay')[0].setValid(true);.
The problem
At one point in the validation function, I'm attempting to call a method on the element, the one added by the HTC script:
el.setValid(true);
However, the IE debugger gets sad and complains that setValid() is not a function. Inspecting it in the debugger confirms this:
typeof el.setValid // "unknown"
Of course, once the page has completed rendering (or whatever period of time is needed for the document to actually be ready has passed), the validation function works as expected (because I'm calling the same validation function on change and blur events as well). That is, when the function is called outside of jQuery's on-DOM-ready function, it works just fine.
Do any of you have any ideas at to what might be happening here? Is jQuery's "ondomready" being registered before the HTC script's "ondomready"? Can I somehow change that order?
I'm currently seeing this behavior in all versions of IE.
EDIT: WORKAROUND
I discovered a workaround. If you take the function call out of the jQuery ready function and throw it at the end of the page, it works (i.e.:)
...
<script type="text/javascript">
txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
</script>
</body>
</html>
I do not know if HTC counts toward page ready but i suspect they do not.
What you might try is check something that only is tru after the HTC hase finished.
You own script should then start something like this:
function MyFunction() {
if(!HTCIsreadyTest()) {
setTimeout(MyFunction, 100);
return;
}
//the rest of your code
}
This basically makes you function check and restart in 100 milliseconds if conditions are not met untill the test succeds.
You could also ad a counter argument increasing it by one for each attempt to have some timeout code trigger if HTC sciprts has not loaded after 2 seconds
The easiest workaround I could find was to move the validation function call out of the jQuery ready() callback and move it to the end of the page:
...
<script type="text/javascript">
txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
</script>
</body>
</html>
However, I found a more elegant solution. Because I seemingly need to wait for all page resources to be loaded, I simply needed to move the function call out of the jQuery ready() callback and instead put it in a window load() callback:
$(window).load(function() { // instead of $(function() {
txtFiscalYearEndDay_Validate(document.getElementById('txtFiscalYearEndDay'));
});
I'm using the latter so I can keep all of the JS code together.

A good cross-browser "ready" event without using jQuery?

I need to create the equivalent of jQuery's ready event without using jQuery. It needs to work on as many browsers as possible and cannot mess up the body.onload handler (i.e. if there's already a handler set, the function shouldn't overwrite it). I checked jQuery's code but don't understand how it works because it uses many jQuery's functions.
Any suggestion on how to do that?
Edit: I have no control over where my code is going to be inserted that's why it needs to play as nicely as possible with the existing body.onload handler. It also means I cannot be sure the code will be inserted at the bottom of the page (most likely it won't be).
Smallest cross browser DOMReady code, ever.
<html>
<head>
<script>
var ready = function (f) {
(/in/.test(document.readyState)) ?
setTimeout('r(' + f + ')', 9) :
f();
};
</script>
</head>
<body>
<script>
ready(function () {
alert('DOM Ready!');
});
</script>
</body>
</html>
This may help:
http://www.freelancephp.net/en/domready-javascript-object-cross-browser/
Non jquery implementation of DOM ready
Simply include your <script> tag at the very bottom. This way, it will only load after all the rest of the content had finished loading.

Categories

Resources