Using an HTML button to call a JavaScript function - javascript

I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.

There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.

I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >

Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)

One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.

Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.

I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

Related

Drop confetti effect when clicking button [duplicate]

I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

Looking for a simple way to click multiple elements with a bookmarklet

I am trying to create a bookmarklet that performs simple functions across different webpages. The idea is that it would be in an easy to find location (on the bookmark bar) and perform the "standard function" on a given page. Instead of looking for a hyperlink or a submit button, I can rely on the bookmarklet to do its duty.
As someone that does not code in javascript, I am having trouble getting the bookmarklet to work on more than one item/page. I started by using the getElementById function successfully
javascript:(function () {
var i = document.getElementById("contactSeller").click()
})()
On another page, there is a button with the ID "sndBtn". Adding another click() function to the code with the second ID, however, doesn't work.
javascript:(function () {
var i = document.getElementById("contactSeller").click();
var m = document.getElementById("sndBtn").click()
})()
As far as I can tell it is because getElementById can only work once on a page. (Removing the first function makes the second one work). Other users have suggested recursive functions with CSS or jQuery but I had little luck getting them to work as bookmarklets.
Can someone help construct a simple function that will run through a list of clicks? It would be nice to have the ability to follow hyperlinks, submit forms, and click buttons i.e. so it is not only a recursive script of the same function. Each of the elements on each page seems to have unique ID's.
Links
GetElementByID - Multiple IDs
https://gist.github.com/aseemk/5000668
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
http://www.dynamicdrive.com/forums/showthread.php?30130-multiple-ID(elements)-inside-document-getElementById(-)
There's no limit to the number of times you can call getElementById. When the element doesn't exist you were probably encountering an exception that caused your script to terminate. You can't call .click() on a null object.
This will check for the existence of the element before clicking:
javascript:(function () {
var i = document.getElementById("contactSeller");
if(i){i.click();}
var m = document.getElementById("sndBtn")
if(m){m.click();}
})()
Did an example and its working good, have a look.
I think what #Rich Moss wrote is right, that document.getElementById("contactSeller") is undefined or that the click function get an exaption, that prevent the code from continue.
function c(v){
console.log(v)
}
document.getElementById("btn1").click()
document.getElementById("btn2").click()
<input type="button" onclick="c(1)" value="btn1" id="btn1" />
<input type="button" onclick="c(2)" value="btn2" id="btn2" />

Javascript auto-calcs won't run in FF, works fine in IE and Chrome

I have the following asp.net textbox defined in markup:
<div class="OptionSelect2">
<asp:TextBox ID="txtCalculateWeightRollSize" CssClass="_100" runat="server"></asp:TextBox>
</div>
In the code-behind, on Page_Load, I am binding the onblur event:
txtCalculateWeightRollSize.Attributes.Add("onblur", "Javascript:RollBWghtPCutoffNWebsCalcs();")
The Javascript (reformatted to more easily to fit into a question format), is as such:
function RollBWghtPCutoffNWebsCalcs() { ZeroPctLbs(); }
function ZeroPctLbs() {
//Get the values
var rollSize = document.getElementById("<% =txtCalculateWeightRollSize.ClientID %>").value.replace("$", "").replace("%", "");
//Get other controls' values
//Make them numbers, if necessary
rollSize = +rollSize;
//convert other controls
//Calculate and assign the result
var result = //math;
document.getElementById("<% =lblCalculateWeightZeroPercentLbsValue.ClientID %>").innerText = result;
}
This works without a problem in both IE and Chrome. However, in Firefox, it fails. In firebug (which I have not used until today), it appears that the onblur event fires, but stepping into the code, when it should be calling RollBWghtPCutoffNWebsCalcs(), it passes over it as though the calling doesn't exist. If I place a breakpoint directly inside any of the Javascript functions, it is never triggered.
The textbox appears to be rendered correctly in HTML:
<input name="ctl00$MainContent$txtCalculateWeightRollSize" type="text" id="MainContent_txtCalculateWeightRollSize" class="_100" onblur="Javascript:RollBWghtPCutoffNWebsCalcs();" />
Here is a JSFiddle that I believe shows the issue. The onblur doesn't work in any browser in the fiddle, but that would be consistent with my experience with Firefox issues in the past. It does work in Chrome and IE when rendered directly, and JSHint indicates that the Javascript is valid.
I suspect something I'm doing isn't completely standard, as Firefox (by my understanding) is pretty much a standards-based web experience. WHY WON'T IT RUN? Please.
Sometimes it's the simple things...
.innerText isn't supported by FireFox. Use innerHTML instead.
Once I stopped using Firebug and switched to FF's built-in debugger, I was able to actually trace my code - I guess I just don't know how to use Firebug. The odd thing that threw me off was that FF would get the values FROM the labels using innerText, and would write them in such a way that subsequent function calls could read the written values, but it would not render the innerText.
tldr;
Use innerHTML to work with label text in Javascript.

Invoking jQuery function without an element

So, I use jQuery quite extensively and I am well aware of the "right" way to do the below, but there are times where I want to solve it in a more generic way. I'll explain.
So, I may have a link, like this: <a href='menu' class='popup'>Show menu</a>. Now, I have a jQuery function that fires on click for all a.popup that takes the href-attribute and shows the <div id='menu'></div> item (in this case). It also handles URL's if it can't find a DOM item with that ID.
No problem here. But, there are times when I don't have the same control over the coe where I can create a selectable target that way. Either because the code isn't created by me or because it is created through a chain of function that would all need a huge ovrhaul which I won't do.
So, from time to time, I would like to have this code:
Show menu
This would be in a case where I can only submit the label and the HREF for a link. No class, no nothing.
Problem here is that the function popup() has no idea about what element invoked it, and in most cases that's not a problem for me, since I only need to know where the mouse cursor was upon invokation.
But in some cases, I use someone elses jQuery functions, like qTip or something else. so I still want to fire off qTip(); when clicking a link that runs this JS function, but what do I attach it to to make it show? I can't just runt $().qTip(); because that implies $(this) and "this" is undefined inside the function.
So how do I do it? Any ideas?
Is there anyway you change the javascript method to javascript:popup('menu', this);? I've used this method successfully many times.
Instead of referring to "this" try referring to $('a:focus') to refer to the link that was clicked.
Here's a quick and, as #Crescent Fresh would add, dirty (☺) sample:
<body>
<p>Show popup()</p>
<div id="menu" style="display:none">Today's menu</div>
<script type="text/javascript">
function popup(elm) {
$('#' + elm).show();
alert( $('a:focus').text() )
}
</script>
</body>
I tried just ":focus" but IE7 returned too much content. I tested this in FF 3.6.3, IE7, Chrome 4.1.249.1064 (all on Windows) and it seems OK, but I see now (when I was just about to hit "Post Your Answer") this relies on the browser's native support for querySelectorAll - see this jQuery Forum post ":focus selector filter?" and the jQuery.expr entry in the jQuery Source Viewer (where it appears Paul's idea was not implemented).
How about
Show menu
Once you get the event object you can virtually do anything to it.

Onclick JavaScript not working properly in IE

Please excuse my ignorance I am not very familiar with JavaScript and have been tasked with repairing a bug by a developer no longer at the company.
The onclick works perfectly in FireFox, however in IE 7&8 (the only ones we test for), it appears to run through the onclick functions properly, then instead of the data being submitted to the form URL in goStep3(), it runs through every onclick on the page, with href="#" then finally submits with incorrect information as the variable has been overwritten 50 times.
view
EDIT:
When I run trackSponsor(62, 64265); goStep3(1896, 64265, 0); return false; in the Developer Tools in IE8 I get an error of returning false outside of a function....removing that it works just fine.
Is the line that I believe is causing the problems?
trackSponsor() is working properly and returns false
goStep3() is quite a large function however it works by retrieving values from 4 other functions within, assigning the values to a URL within theAction
It completes the function by EDIT:
var yr = $("#find-yr").attr('value');
var me = $("#find-me").attr('value');
var mo = $("#find-mo").attr('value');
var keywords = $("#find-keywords").attr('value');
var theAction = PATH_BASE+'find/step3/'+p_term+'/'+p_id+'/'+p_l_id+'/';
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
return true;
I have tried returning false from this function, as well as changing the document.FindForm.submit() to the 'correct' syntax of document.forms['FindForm'].submit() and it still does not submit until running through all of the other onclick s on the page.
Thanks in advance!
Notes:
jQuery is being used as well.
Javascript is not throwing any errors.
This works fine in FireFox
I can see it going through all of the other functions in the other onclicks using Developer Tools and stepping through the page it does not submit the results of goStep3 until it has gone through all of the other onclick functions on the page.
"posting my earlier comment as an answer"
I see a lot of jQuery being used with attribute selectors, so plz check the code against those.
EDIT:
I noticed ur unfamiliar with JavaScript... so in-case u didnt know, a jQuery selector, will select all tags matching a certain "selector-filter" and perform a certain action on them... so if there is a selector that selects all A tags with a href attribute (or maybe another common attribute between them...) then that would be the cause of your problem.
EDIT: -after you posted your answer -
glad you found an answer...
though it is alittle werid,
cause according to your question it goes through "every element with href="#" ...
However According to msdn, Event bubbling simply passes these unhandled events to the parent element for handling. not through "similar" tags :)
oh well..nothing is logical when it comes to IE
I would start by removing "return false;" from the onClick event since it really isn't doing anything.
try changing
href="#"
with
href='javascript:void(0)' .
I can't say for sure where things are going wrong, but I discourage using a form's name attribute to reference it like you have done here:
document.forms['FindForm'].action = theAction;
document.FindForm.submit();
Why not try the following jQuery:
$("form:FindForm").action = theAction;
$("form:FindForm").trigger("submit");
You should also check that $("form:FindForm") is indeed referencing the desired form element.
The problem was called because of how IE uses the bubble! Thanks all for your help, I have included the code solution to be placed in goStep3().
var browserName = navigator.appName;
if (browserName == "Microsoft Internet Explorer") {
window.event.cancelBubble = true;
}

Categories