The click event from javascript on a button doesn't fire - javascript

So, I was going through a tutorial on event handlers. I created a button as instructed and then when I click on it, I wanted an alert to be displayed. Thats it. But it wouldn't work. Here's my html code:
<button id="submit">Submit</button>
And here's my javascript code:
var myButton = document.getElementByID("submit");
myButton.onclick = function(){
alert("YOu clicked on this button");
}
I am using external js file and I've included it in the html from the head of the document.

document.getElementByID("submit"); -- it's Id instead of ID
Edit: I feel very bad for giving this one-liner as an answer, so to add to what others have said about learning how to use the browser's console as a debuggining tool, you should try to find an IDE/text editor with auto-completion to save you such headaches especially when you're just starting out.

You may have an issue where document.getElementById() is happening before the element is created on the page. Try including your JavaScript in an onload event, or include it after the button in your HTML.

As previously stated, use document.getElementById("submit") with lower case Id. Also, you may want to use setAttribute so the alert fires when the button is pressed instead of immediately opening a popup when the alert line is encountered.
<script language="javascript">
var myButton = document.getElementById("submit");
myButton.setAttribute("onclick", "alert('You clicked on this button')");
</script>

change from document.getElementByID to document.getElementById and make sure your script stay below all the elements in the body. Example:
<body>
<button id="submit">Submit</button>
<script type="text/javascript">
var myBtn = document.getElementById("submit");
myBtn.onclick = function()
{
alert("this is a click event button");
};
</script>
</body>
or you can put the script inside the <head></head> by add this event below to your script:
function initialize()
{
// paste your code in here
}
document.addEventListener("DOMContentLoaded",initialize,false);
Hope it work!

it maybe a typo. It is getElementById not ID

Related

What eventListener Should I use here?

I am creating this compiler and my problem is that I need to detect the changes in the upper text box and I was able to detect all changes except the change when the user clicks the clear button and the text clears up in the box. Can anyone please suggest what js event listener I can use to detect this?
You can use the simple addEventlistener as follow:
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id="myBtn">Try it</button>
<p id="demo">Hello</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
document.getElementById("demo").innerHTML = " ";
});
</script>
</body>
</html>
As you can see here, the p tag earlier had a value but after the button is clicked the value into p tag is set to the value assigned in the js. So what you have to do is to make the value inside your text field to null by using the .innerHTML=" "
onclick event will be helpful.
let button = document.getElementById('clear_Code');
let textbox = document.getElementById('textbox');
button.onclick = function() {
textbox.innerText = '';
}

Unexpected Javascript onkeydown event and document.write

I am learning Javascript and when I am testing some features, I found some problems. Here are my codes:
<script>
function onCreate() {
var body = document.getElementsByTagName('body')[0];
body.focus();
body.onkeydown = function(e) {
if (e.keyCode == 32) {
alert(1);
sayHey();
}
}
}
function sayHey() {
document.write("Hey ");
document.write("May");
}, 30);
</script>
</head>
<body onload="onCreate()">
</body>
As you may try, onkeydown event works perfectly when I do not include sayHello() function, which make use of setInterval.
When sayHello() is included, when I click space bar, "Hey May" is created which is as expected. However, when I click space bar once more, no alert message and no new "Hey May" is raised. It seems that onkeydown() function do NOT work anymore. Why is it the case?
In addition, when I change document.write(brabrabra) to the below one, it works.
var newParagraph = document.createElement('p');
var text = "Hey May";
var textNode = document.createTextNode(text);
newParagraph.appendChild(textNode);
body.appendChild(newParagraph);
Why is it the case? Can someone explain to me please? Thanks a lot.
After the document has been parsed, the current document is closed and any use of document.write() will clear the current document and open a new blank document, thus clearing any event handlers or content you previously had.
So, in your specific example, the first key press triggers your event handler. That shows the alert(1) and then calls sayHey() which calls document.write() which clears the current document and thus your event handler is no longer there. So, for the second press of the space bar there is no event handler in place and nothing happens.
So, if you want to add content to the document after it has been loaded, then you should add the content with something like document.createElement() and .appendChild(), not document.write().

Create onchange event with javascript in Firefox

I've been working on trying to trigger an onchange listener with java script in Mozilla Firefox. I've found a lot on Stack Overflow posted about this, but nothing seems to be working for my unique case.
I've created this HTML with a onchange listener from an onchange event using this helpful post (JavaScript OnChange Listener position in HTML markup). Here's my code:
<HTML>
<head>
<script type="text/javascript">
window.onload= function () {
if(window.addEventListener) {
document.getElementsByClassName('search-box')[0].addEventListener('change', loadXMLDoc, false);
} else if (window.attachEvent){
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);
}
function loadXMLDoc(){
alert('It worked');
}
}
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
}
</script>
</head>
<BODY>
<input type="text" class="search-box" placeholder="Player Search">
<br \>
<button type="button" onclick="addTextCallListener()">Click Me!</button>
</BODY>
</HTML>
I also saved it as this jsfiddle (for some reason I had to keep it all together for it to work, I couldn't break it up into js and html).
https://jsfiddle.net/josephfedor42/crogL0zd/1/
If you play with this jsfiddle you can see that entering text and pressing enter will trigger the listener and the pop up with the message “It worked” will appear.
But if the button “Click Me!” is pressed it only changes the value of the text box, and the onchange listener is not called.
I realize I could easily add an onchange event to this button. But I want to to trigger the listener by programatically/ superficially using javascript in my addTextCallListener() function.
I've tried the simple stuff, like calling
searchBox.onchange();
searchBox.focus();
searchBox.click();
And a combination of these to add and remove the focus. But it doesn't seem to work. I've found quite a few posts on triggering an onchange event, but nothing that works in Firefox.
Any help would be appreciated.
Thanks for that link of a possible duplicated question. I had checked out that link before.
But I gave it a try again. I saved the jsfiddle from them both and neither one work.
My implementation of Dorian's answer
https://jsfiddle.net/josephfedor42/zaakd3dj/
My implementation of Alsciende's answer
https://jsfiddle.net/josephfedor42/xhs6L6u2/
emphasize mine
According to the mdn page about the change event,
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user.
and to whatwg specs :
When the input and change events apply (which is the case for all
input controls other than buttons and those with the type attribute in
the Hidden state), the events are fired to indicate that the user has
interacted with the control.
Therefore, setting the value of an input is not an action "committed by the user" nor a sign that "the user has interacted with the control", since it was made by the code.
So, even if the specifications for this event are kind of unclear, the event should not fire when you change its value by code.
Something like this should work:
function addTextCallListener() {
var searchBox = document.getElementsByClassName("search-box")[0];
searchBox.value = "Hello";
//fire the event
if (document.createEvent) {
searchBox.dispatchEvent('change');
} else {
searchBox.fireEvent("onchange");
}
}
Here is the code I needed to add to my function addTextCallListener:
var evObj = document.createEvent('HTMLEvents');
evObj.initEvent( 'change', true, true );
searchBox.dispatchEvent(evObj);
I updated the jsfiddle. The working code is here https://jsfiddle.net/josephfedor42/crogL0zd/7/
Replace onchange with change in this part:
document.getElementsByClassName('search-box')[0].attachEvent("onchange", loadXMLDoc);

javascript popup alert on link click

I need a javascript 'OK'/'Cancel' alert once I click on a link.
I have the alert code:
<script type="text/javascript">
<!--
var answer = confirm ("Please click on OK to continue.")
if (!answer)
window.location="http://www.continue.com"
// -->
</script>
But how do I make it so this only runs when clicking a certain link?
You can use the onclick attribute, just return false if you don't want continue;
<script type="text/javascript">
function confirm_alert(node) {
return confirm("Please click on OK to continue.");
}
</script>
Click Me
Single line works just fine:
<a href="http://example.com/"
onclick="return confirm('Please click on OK to continue.');">click me</a>
Adding another line with a different link on the same page works fine too:
<a href="http://stackoverflow.com/"
onclick="return confirm('Click on another OK to continue.');">another link</a>
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
click me
In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML
HTML:
<a id="theLink">Click Me</a>
I could use the following jQuery to hookup an event to that specific link.
// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {
// The '#theLink' portion is a selector which matches a DOM element
// with the id 'theLink' and .click registers a call back for the
// element being clicked on
$('#theLink').click(function (event) {
// This stops the link from actually being followed which is the
// default action
event.preventDefault();
var answer confirm("Please click OK to continue");
if (!answer) {
window.location="http://www.continue.com"
}
});
});

Checkbox inside an anchor click behavior

Consider following snippet:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<form>
<a id="a" href="http://google.com">Goooooogle</a>
</form>
<script>
$(function() {
var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
e.stopPropagation();
// do something useful
});
});
</script>
</body>
</html>
I want to get a checkbox inside <a>, and get following on-click behavior:
Toggle check mark normally as usual
Do something useful like AJAX-request
Stay on this page, i.e. not be redirected to an a href
Also I want to not override default behavior if I click anywhere in a, but not on checkbox. I.e. I want to allow to execute all event handlers associated with a click itself.
I thought that should be pretty easy, but I can't get desired behavior. Either:
I get redirected to Google if I put a code provided.
I don't get check mark toggled if I use e.preventDefault() of return false;. Furthermore in that case checkbox ignores explicit checkbox.attr('checked', 'checked') and all other possible ways to set the check mark.
Where is the catch?
UPD: This works as expected in Chrome, e.g. I'm not redirected on click, but fails in Firefox. Is there cross-browser way?
Well, it looks like a known Firefox bug, which leads to following link on checkbox click regardless of handlers' code. As a bit dirty workaround one can use:
var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
setTimeout(function() { checkbox.prop('checked', !checkbox.prop('checked')); }, 10);
// do something useful on clicking checkbox and but not surrounding link
return false;
});
I know this is an old question but some may still be curious since it was never really fully answered without a messy hack or workaround. All you have to do is simply check where the event's target originated.
So using your example (jsfiddle):
// Don't change pages if the user is just changing the checkbox
$("#a").click(function(e) {
//e.preventDefault(); // Optional if you want to to keep the link from working normally
alert("Click came from: " + e.target.tagName);
if (e.target.tagName != "INPUT") {
// do link
alert("Doing link functionality");
} else {
// do something useful
alert("Doing checkbox functionality");
}
});
I Know this question is over 5 years old, but I had the same issue recently and the work-around I found was to add an onclick function to the checkbox and in that function call event.stopImmediatePropagation().
from w3schools: "The stopImmediatePropagation() method prevents other listeners of the same event from being called"
ie...the anchor.
function checkbox_onclick(event){
event.stopImmediatePropagation();
}
here's a modified script
var checkbox = $('<input type="checkbox"></input>');
var a = $('#a');
a.unbind("click").click(function(e) {
e.preventDefault();
checkbox.attr('checked', !checkbox.attr('checked'));
});
checkbox.prependTo(a);
checkbox.click(function(e) {
e.stopPropagation();
// do something useful
});
i unbind the click event on the <a> and rebind it with a event to check/uncheck the checkbox and also prevent the default.

Categories