Insert a Print Button for A website Form [duplicate] - javascript

This question already has answers here:
link to Print in a webpage
(2 answers)
Closed 8 years ago.
I am trying to add a print button for a form on the website that I maintain for a voluntary organization in Scotland. I would stress that I am not an expert in either HTML or Javascript but do my best.
The answer given by Murali to question 20101409 on 20th November 2013 looks as if it should work but does not. I suspect that I not named or defined something correctly.
My test webpage is: http://clanmacthomas.co.uk/Pages/TestCalculations.aspx

I strongly discourage the use <a href="javascript:..something.."> for any purpose, and especially the use of links to perform actions, preferring buttons instead.
If you have
<div>stuff</div>
<div>more stuff</div>
<input type="button" id="print" value="Print this page">
You can later attach a handler to it by using
<script>
document.getElementById("print").addEventListener("click", function() {
if (window.print) window.print();
});
</script>
If you are likely to want a print button on more than that one page, put that code in a .js file
/* printer.js */
document.getElementById("print").addEventListener("click", function() {
if (window.print) window.print();
});
There are nicer ways to do it if you are using jQuery, but you didn't mention that so I'm avoiding it.
You may want to read the SO question "Correct usage of addEventListener() / attachEvent()" since older versions of Internet Explorer use attachEvent instead of addEventListener.

To add a link that will open the print dialog on a webpage, include this link somewhere:
Print

Related

How do I set specific key for keydown event listener? [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>

Can you invent html attributes? [duplicate]

This question already has answers here:
Custom attributes - Yea or nay?
(15 answers)
Closed 9 years ago.
I am working on a website using HTML5. I have a jQuery script that shows a custom tooltip on all elements that have the title attribute. I also have a script that makes an alert message appear when the user clicks a picture. The alert message will say what the title attribute equals. Unfortunately the tooltip script and the alert script interfere with each other.
My question is:
Can I make up an attribute?
Not exactly, but HTML 5 provides data-*.
In html5 , use data-XX to produce extra attributes.
see : http://www.w3.org/html/wg/drafts/html/master/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes
You can make an aditional attribute, just by naming it.
<img src="abc.jpg" data-opens="abc" data-test="abc" id="image" />
And access it in jQuery by typing
$("#image").attr("data-opens")..
Like:
alert($("#image").attr("data-opens") + " " + $("#image").attr("data-test"));
Edited, thanks to GCyrillus.
Specifically answering you question: you can make up attributes.
But your HTML will no longer be valid and since you are adding them just to store information, you should use de data-* form to add you own data storage for an element, plus it will still be a valid HTML

how to change a button text in jQuery mobile [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
change text on button using jquery mobile.
I need to change a button text, I am using jQuery mobile.
Here is my html:
<fieldset>
<div><button type="submit" id="login_var">Login</button></div>
<div><button type="reset" >Reset</button></div>
</fieldset>
I have tried all of the examples on this page:
LINK and nothing is working for me.
Please help
I've had to do the same thing before, it's really not as obvious to do as it should be. Since jQM adds span tags inside your button, you need to change the value inside the span:
$("#login_var .ui-btn-text").text("NewText");
Similarly, if you wanted to change the icon, you could do:
$("#login_var .ui-icon").removeClass("ui-icon-arrow-l").addClass("ui-icon-arrow-r");
Edit:
Sorry I just noticed the link you posted in the question has the same solution, and you said that doesn't work for you. Maybe if you changed your buttons to
<a data-role="button"></a>
Instead of <button></button>?
Yeah you can use
$(function(){
$('#login_var').text('Ok').button('refresh');
});
As per http://jquerymobile.com/test/docs/buttons/buttons-methods.html, there are only three methods you can call on a button.

Why is using "javascript: <code>" bad? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do you ever need to specify javascript: in an onclick?
To execute JavaScript on a DOM event, you could use something like this:
<div onclick="alert('Alert');">Alert</div>​
Something like this seems to work as well:
<div onclick="javascript: alert('Alert');">Alert</div>​
However, I've heard that the second example is "bad" and that the first example should be used over the second.
Is this bad? If so, why is this bad? What is the difference between alert('Alert') and javascript: alert('Alert')?
What about using it in <a> tags (if it is any different)?
Alert
Edit: To clarify, I am asking about the javascript: part specifically, and not how I have inline JavaScript mixed in with my markup. Sorry about the confusion.
Oh the wonderful confusing world of JavaScript. The code you posted probably doesn't do what most programmers think it's doing.
There is a difference between each of the following lines:
<a onclick="alert('Hello World!')"...>example</a> //V1
<a href="javascript: alert('Hello World!')"...>example</a> //V2
<a onclick="javascript: alert('Hello World')"...>example</a> //V3
although they all will alert Hello World!.
The first (V1) has an inline click event bound via the [onclick] attribute. It may also contain an [href] attribute that navigates to another location after the [onclick] attribute has executed, or any number of other click events bound in the code, assuming the default behavior hasn't been prevented.
The second (V2) has an executable javascript: url set as the [href] attribute. It might also contain an [onclick] attribute or other click events bound in external scripts.
The first and second examples (V1 & V2) have identical code executed, which is:
alert('Hello World!')
The third example (V3) has an inline click event bound via the [onclick] attribute, just like V1, however the code being executed is different. The executed code is:
javascript: alert('Hello World')
Although it looks like a javascript: url, it's actually just using a label in javascript.
Labels in JavaScript are useful for skipping out of nested loops, as in the following example code:
label: for (i = 0; i < 5; i++) { //labeled line
for (j = 0; j < 5; j++) {
console.log(i, j);
if (i === 2 && j === 3) {
break label; //this jumps out of both for loops
}
}
}
In most inline JavaScript, it's misused because the author doesn't understand the difference between the three formats.
Why is using javascript: <code> bad?
That's a leading question. It assumes that using javascript: <code> is bad.
javascript: <code> isn't bad. It's a tool. Tools aren't inherently good or bad, only the people using the tools are. You wouldn't call a hammer "bad", even if someone used it as a weapon.
javascript: <code> has some nice uses. You shouldn't use it for most cases because it's the wrong tool for the job, however if you're writing a bookmarklet, you'd be required to use the javascript: <code> format.
Additionally, there are a few niche contexts where it could make sense to leave javascript inline. An example of this would be to add a simple print button to the page:
Print
Although even this example could be easily replaced by a class and externalizing the javascript:
Print
<script>
//jQuery used for brevity
$(document).on('click', '.print', function () {
window.print();
return false;
});
</script>
There's no real problem with using the javascript: labels. It's just considered bad style most of the time.
an onclick-handler already is JavaScript, so repeating that is just senseless, redundant information (in fact, it's chaging the code thats executed by adding a label named javascript - but in most cases this shouldn't have any effect).
JavaScript code in a href attribute would be placed more appropriately in an onclick handler, so you can use the href to provide a link for users that have JavaScript disabled. This is called Progressive Enhancement.
For more detailed information, you may want to take a look at this great blog-post about "The useless javascript: pseudo-protocol"

javascript that produces functioning javascript

can you write javascript that produces/writes/etc. functioning javascript?
for example, have a link that has a function tied to it that when clicked produces a functioning javascipt snippet? The snippet could deal with a completely other elements.
For example
Link #1(has the javascript function that produces javascript) Link #2(does absolutely nothing for now)
Click on link #1(produces javascript snipped that says "when link #2 is clicked document.write('hello')"
Clicking on link #2 now produces "hello" whereas it previously did nothing. Is that possible?
Yes, you can dynamically assign event handlers described in text.
However, dynamic code generation is far more difficult than it sounds unless you're just following basic patters and replacing certain variables. Writing programs that write programs has long been a fascination of the computer industry, and this gave way to functional programming, which can be done in javascript.
Create the input/delete keys on the onClick handler for the datepicker, you can attach date information (or other data) when the input(s) are created. Now, you should look into $.delegate() for how to bind handlers to those inputs created. $.delegate can bind handlers to elements that are not created yet, so when they are created they will fire a handler. By storing date relevant information in the inputs via $.data() or data- attributes you will have context aware handlers for dealing with things.
If I understand your question correctly, you could do what you want with the code below.
Not sure why you'd want to do this, though.
can you write javascript that produces/writes/etc. functioning javascript?
You can do this the way I did it, or by using eval -- though, as many coders have pointed out, eval is evil!
<html>
<head>
<script type="text/javascript">
function initLinks(){
document.getElementById("link1").addEventListener("click", function(){
document.getElementById("link2").addEventListener("click", function(){
document.write("hello");
}, false);
}, false);
}
</script>
</head>
<body onload="initLinks()">
<a id="link1">Link 1</a>
<a id="link2">Link 2</a>
</body>
</html>

Categories

Resources