Want to print a particular section of a page using JavaScript - javascript

I'm basing my code off of this solution by Ben Nadel
Here is the code included in the page
<script type="text/javascript">
// When the document is ready, initialize the link so
// that when it is clicked, the printable area of the
// page will print.
$(function() {
// Hook up the print link.
$("a").attr("href", "javascript:void(0)").click(function() {
// Print the DIV.
$( ".printable" ).print();
// Cancel click event.
return(false);
});
});
</script>
Here is a codepen
The Buttons are not working in the pen but do work locally.
What i'm trying to do is have the user print the contents of each list item which as you can tell is a Q&A so essentially have the user be able to print each Q&A pair when they click the button.
I've only included two to provide the minimal example to help me figure out where my error is.
What's happening is that no matter which button I click it will always print the first "li" with the class of "printable" and i'm not sure how to distinguish each section so that the button understands to only print 'this' and not the first li that has that class which is what it's doing.
Obviously this is a problem since each Answer will have a "click to print" button and I don't want them to all print the same Q&A pair.
Does this make sense?
My instinct is to have some kind of loop in play or iterate through an array, but i'm very new to JavaScript so i'm looking for a moderately challenging solution.

Yes, it does make sens. You are selecting elements to print with $('.printable').print([1]); It means, print the first element that match my selection, that is .printable. The first element that has the class printable. What you should do is bind each button with the appropriate section and use IDs instead of classes to select elements. As IDs are unique !
function(){
$('.printBtn').attr('href', 'javascript:void( 0 )').click(function(){
//select the corresponding section, first parent li that have .printable class
var section = $(this).closest("li.printable");
// Print Div
$(section).print([1]);
// Cancel click event
return(false);
});

You can use simple java script to print specific div of a page
var prtContent = document.getElementById("your div id");
var WinPrint = window.open('','','letf=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

Related

How to get ids from divs that were dragged into a drop zone on button click javascript

I'm trying to find a way to get the ids from dragged divs after they are in the drop zone.
All the drag components have an id from drag1 - drag8 and the drop zone is div drop zone. Because there are no divs in the drop zone when the page loads I want to gather the ids on a save button for now with a text box entry and drop down menu select.
I have tried the code below:
$(document).ready(function() {
$("#dropzone div").click(function() {
var index = $("#dropzone div").index(this);
$("#dropzone_drag").html("Index " + drag + " was clicked");
});
});
And I use jQuery for the text box, which works nicely:
$(document).ready(function() {
$('#save').click(function() {
alert($('#name').val());
});
});
How do I find the ids from dragged divs after they are in the drop zone?
After playing around i came up with the following:
var ids = {};
$("#dropzone>div").each(function(i){
ids[i] = $(this).prop('id');
});
which at the moment says undefined, but i did manage to put it on the save button so it no longer pops up when i open the page.
Any suggests please?
In my comprehension .index(this) returns the index of the element relative to the list "#dropzone div"., which may or may not contain the elements in the order you want. But if all your elements have a common class, say ".foo_bar" it probably would be easier to know the id given an clicked element.
Otherwise, as you're using this on the function, if this is one of your "drags" it is probably easier to pick the id from this than to try the indexes.
Try doing it like that and maybe it'll word better.
ids = {};
$("#dropzone>div").each(function(){
ids[$(this).prop('id')] = $(this).prop('id').replace(/[^0-9]/g, '');
});
the code .replace() means that we are removing characters (in this case anything that isn't a number) from the string so we end up with it's true number. Instead of it's place in the DOM.
If i didn't comprehend well your problem, correct my comprehension errors and i will edit the answer. And an html of the zones would be nice ;)
The following code worked for me:
<script>
var div = document.getElementById('dropzone')
</script>
and on the button i added:
alert( div.innerHTML )
The result gave me all of the div information from it's html page so i could select the information i wanted to push to the database.
Thank you all for you input and advice.
Matthew

Show and Hide DIV based on users input

I have an input box for zip code entry's, when a user inputs a zip code I want to show a specific DIV.
It starts with everything hidden except for the input box and go button, then the user enters a zip code and the matching DIV shows (the DIV ID will be the zip code) There maybe hundreds of DIVs and possible inputs.
Here is what I have so far, note it starts showing everything (not what I want) but it kinda works
$(document).ready(function(){
$("#buttontest").click(function(){
if ($('#full_day').val() == 60538) {
$("#60538").show("fast"); //Slide Down Effect
$("#60504").hide("fast");
}
else {
$("#60538").hide("fast"); //Slide Up Effect
$("#60504").show("500");
}
});
$("#full_day").change(function() {
$("#60504").hide("500");
$("#60538").show("500");
});
});
LINK to working File http://jsfiddle.net/3XGGn/137/
jsFiddle Demo
Using pure numbers as id's is what was causing the issue. I would suggest you change them to
<div id="zip60538">
Welcome to Montgomery
</div>
<div id="zip60504">
<h1>Welcome to Aurora</h1>
</div>
In the html (as well as in the css and the js as can be seen in the linked fiddle)
This will allow them to be properly referenced in the DOM
edit
jsFiddle Demo
If you had a lot of these to handle, I would probably wrap the html area in a div to localize it and then use an array to store the accepted zip codes, and make use of both of those approaches in the click event
$(document).ready(function(){
var zipCodes = [60538,60504];
$("#buttontest").click(function(){
var zipIndex = zipCodes.indexOf(parseInt($("#full_day").val()));
$("#zipMessage > div").hide("fast");
$("#zip"+zipCodes[zipIndex]).show("fast");
});
});
Start off with all the div's style of display: none;. On your button click simply check that a div exists with that ID, if so, hide all others (use a common class for this) and show the right one:
$("#buttontest").click(function() {
var zip = $("#full_day").val();
if ( $("#" + zip).length ) {
$(".commonClassDiv").hide();
$("#" + zip).show();
}
});

How to remove elements once it was created by jquery

I am new to JQuery, I was wondering why my script is not working. I have been reading through the API and I did exactly what it says but I am still not getting what I was expecting. Please find the script below:
//To infinitely add images
$('.add_upload_image').on('click', function(){
$('.upload_image').append('<input type="file" name="userfile[]"/><br/>');
});
//To remove the last child of the .upload_image
$('.remove_upload_image').on('click', function(){
$('.upload_image input:last-child').remove();
});
So I am sure you understand what I am trying to achieve. But basically, i have a text that says 'click to add more uploads' which is wrapped around with the .add_upload_image then when the user clicks on it, it adds the input element to the div class .upload_image. Works fine. However, when the user clicks on the 'click to remove' which is wrapped in .remove_upload_image and I am aiming at the last child of the .upload_image that is input and it is not removing.
What am I doing wrong here?
Many thanks in advance.
You have to use :last, not :last-child ( the <br> element is the last child ):
$('.remove_upload_image').on('click', function(){
$('.upload_image input:last').remove();
});
You should probably remove the <br> element as well:
$('.remove_upload_image').on('click', function(){
var el = $('.upload_image input:last');
el.add(el.next('br')).remove();
});
FIDDLE
$('.upload_image').last().remove()
This should work.

Link changing class of parent <div>, content of two <iframe> elements

Interesting (and rather complex) issue here...
What I have is a page with two iframes and a set of links at the top, each contained inside a div with an image background. What I want is for the contents of both iframes to change (to two separate html documents) when the link is clicked, and for the background image of the link's parent div to also change. I also, however, want the parent div to automatically change back to the original class when a different link is clicked (i.e. I have two classes, 'active' and 'waiting'. When a link is clicked (and its contents subsequently displayed in the iframes) I want it to switch to class 'active'. At all other times, though, (including after a different link might be clicked and become active) I want it to go back to using the 'waiting' class.)
Here's my current code / markup:
Javascript:
function changeFrame(link) {
$('#first iframe').src=link.href;
$('#second iframe').src= (Here would be the second link, not sure how to define that)
link.ParentNode.addclass("activebutton");
HTML:
<div class="waitingbutton">
<a href="yes.html" (Somewhere here would be the second link for the second iframe) class="waitingbutton" onclick="changeFrame(this);
return false;">Button Text</a>
</div>
(After this come four more divs, each identical bar Button Text and links)
As I suspect you can tell, I'm really just guessing here. Still not hugely familiar with Javascript, hoping someone can help me out.
You seem to be using jQuery.
Here's an ugly way to do it; but it works:
Button Text
And your JavaScript:
function changeFrame(link) {
$('#first iframe').attr("src", $(link).attr('href'));
$('#second iframe').attr("src", $(link).attr('secondary-href'));
return false;
}
Note that it'd be more idiomatic jQuery to do this without any onClick handlers, but simply initialise it all in your <head>/<script> from the beginning:
<script type="text/javascript">
$(function() {
$("a.iframe-link").click(function(event) {
$("#first iframe").attr("src", $(link).attr("href"));
$("#second iframe").attr("src", $(link).attr("secondary-href"));
// Whatever used to be the activebutton, make it 'waitingbutton', and remove
// the 'activebutton' class.
$(".activebutton").
addClass("waitingbutton").
removeClass("activebutton");
// Remove .waitingbutton from this, add .activebutton.
$(this).removeClass("waitingbutton").addClass("activebutton");
// Don't allow the link's default action (to follow the href in the normal
// way).
event.preventDefault();
});
});
</script>
Then later:
<a class="iframe-link waitingbutton" href="yes.html" second-href="whatever.html">Hello!</a>

Span tag inside contentEditable div needs keypress event

I have the following div in my html code:
<div id="expanderInput" tabIndex="1" contentEditable></div>
I'm using a contentEditable div as a simple, cross-browser method of making an auto-expanding textbox. I'm also doing input validation on what the user enters into this div. It is supposed to be a list of email addresses separated by commas. When the user tries to submit incorrect information, my Javascript chunks up the input and highlights in red all the incorrect chunks.
//split the address into the comma-separated chunks
var chunks = splitForward(forwardsTo);
//Grab each bad chunk one at a time and stick it in a span with a red-colored text
for(var i = 0; i < invalids.length; i++)
{
var current = chunks[invalids[i]];
current = '<span class="highlighted">' + current + '</span>';
chunks[invalids[i]] = current;
}
$("#expanderInput").html(chunks.join());
initHighlighted();
The array 'invalids' holds the indexes of all the bad chunks. Everything up to this point works fine. But once the user starts typing inside the red text I need the red to disappear, but just in that span. For example, if there are two bad chunks, each highlighted in red, and the user starts fixing one, the other needs to stay red.
I've tried attaching an event listener to the spans:
initHighlighted = function()
{
$(".highlighted").keypress(function()
{
alert("It works!");
});
};
But the event never happens, even when the user edits the text in red. Using browser's developer's tools, I can see that the event handler is there, it is just never set off. Is it the contentEditable attribute on the div causing the span from receiving the event? I've also tried making the spans themselves contentEditable, but the behavior is still the same.
Unless I'm mistaken, this should solve your problem :
initHighlighted = function()
{
$(".highlighted").live("keypress",function()
{
alert("It works!");
});
};
Because your spans are added after the initial loading of the DOM the keypress event listeners haven't been attached as there was nothing to attach them to. Jquery's live sorts this out for you by attaching those listeners to, in this case, anything with the class 'highlighted' no matter when they are added to the DOM.
Read the documentation on the Jquery site to get a much better explanation than I could give you : http://api.jquery.com/live/
EDIT : My apologies for not reading your question properly and realising that your were attaching the keypress listener after after the 'highlighted' spans were added.
Have you read this though :
Keyboard events for child elements in a contenteditable div?

Categories

Resources