I have a project in JQuery that requires a user to click a button to download a PDF before proceeding to the next screen. I've tried writing a conditional statement that would perform this action:
downloadPDF.js
function getPdf () {
$('.button-rounded').click(function () {
(pdf.fromHTML($('.message-container').html(), 30, 30, {
'width': 400,
'elementHandlers': specialElementHandlers
}));
pdf.save('example.pdf');
});
}
// continue new plan
function getPlan () {
$('.button-rounded-negative').click(function () {
var url = "http://www.example.com";
window.open(url);
})
}
if ($(getPdf).onClick(false)) {
$(getPlan).attr('disabled', true)
}else{
if ($(getPdf).onClick(true)) {
$(getPlan).attr('disabled', false)
}
}
The goal is to disable the getPlan button until the getPDF button is clicked which starts an automatic download of the file.
Unfortunately, I haven't got it to work yet. If I use ($(getPdf).click(false)) & the displayed code, both button are still enabled. If I use .onClick both buttons are then disabled.
How do I handle this event? Up until this point, I've mostly written apps/conditional statements in React so I'm not quite understanding where I am going wrong in my conditional statement logic.
This isn't how Javascript works. You cannot put event handlers in if statements. You should also not nest your event handlers (as I assume getPdf() and getPlan() are called from onclick attributes).
Instead you need to enable the second button in the DOM within the click handler for the first button. Try this:
jQuery(function($) {
$('.button-rounded').click(function () {
pdf.fromHTML($('.message-container').html(), 30, 30, {
'width': 400,
'elementHandlers': specialElementHandlers
});
pdf.save('example.pdf');
});
$('.button-rounded-negative').click(function () {
var url = "http://www.example.com";
window.open(url);
$('button-rounded').prop('enabled', true); // enable the button here,
// assuming it starts in a disabled state
});
});
Note that you should remove the implied onclick attributes from your HTML and only use the above JS.
Related
I have a web application with a medium amount of ajax requests.
I load all jquery and jquery widgets on head then i load my base.js before close body tag.
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
}
SCRIPT BLOCK TO LOAD BASE SCRIPTS ON EVERY AJAX REQUEST
$(document).ajaxComplete(baseScripts);
The problem is after every ajax request the base scripts its called again and them opening dialog multiple times and attaching select2 multiples times too.
How i can detect if widget is already attached into element or class?
Execute scripts on every ajax request (like i did) its a bad pratice?
It doesn't make sense that you will want to re-bind the click event and select2 on ajaxComplete. They should be a one-time binding, in which case, you can just do:
$(document).ready(function(){
baseScripts();
function baseScripts() {
$(".open-dialog").click(function (event) {
event.preventDefault();
event.stopPropagation();
alert("Opening dialog");
href = $().buildUrl($(this).attr("href"), "&isAjax=true");
$().createDialog(href, "Window Title");
return false;
});
$("input:hidden.select").each(function () {
var element = $(this);
if (!($("#s2id_" + element.attr("id")).length)) {
$(element).select2({
// select2 properties...
});
}
});
}
});
Initially, I had a problem that a click event was firing multiple times, but I have managed to overcome that with a probably over use of unbind() and one() as you'll see in my code below!
What I have here is some code which opens up a universally usable Modal window which I use for various things, including, in some cases a password form.
I don't think you need the HTML so I won't post that.
When a button, or an action causes the window to be required, I call the function like this:
showModalAlert(type, theWidth, theHeight, title, html, confirmThis, denyThis)
The first three variables determine how the window will look, title and html determine the content and confirmThis and denyThis are functions set immediately prior to calling this function and determine what the action should be if this is a confirm window and the confirm or deny buttons are press.
In the case of a security window, the confirm button is replace by a "sign it" button which submits a simple password form and returns a User Id from database. If a User Id is successfully returned, the script programatically presses the confirm button and in turn runs it's function as per the call to the inital opening of the modal window.
My problem is that if an incorrect password is entered, or a user cancels the window and then later without refreshing the browser window, re-enters the password correctly, the confirmThis() function is performed twice (or as many times as the incorrect password/cancel action was performed).
So, clearly, what it is doing is "remembering" the confirmThis function each time.
As I said, initially, the password success function was clicking confirmIt twice, copious use of one() has fixed this, it is now definitely only clicking confirmIt once, but it is still performing the function multiple time.
How can I clear this function and ensure it is only performed once?
The function from which I am calling the modal window looks like this:
$('#saveDelivery').click(function () {
function confirmIt() {
formData = (JSON.stringify($('#delDetail').serializeObject()));
saveData(formData);
$('#saveDelivery').removeClass('centreLoader');
};
showModalAlert('security', '300px', '185px', 'Security!', 'You need to "Sign" this action.', confirmIt, '');
});
It's simply a click on the saveDelivery element, the confirmThis function is declared at this point and submits an AJAX form
the actual showModalAlert function is below:
function showModalAlert(type, theWidth, theHeight, title, html, confirmThis, denyThis) {
// stuff that opens the alert window \\
if (confirmThis == '') {
$('#confirmIt').one('click', function () { $('#closeAlert').one('click').click(); });
} else {
$('#confirmIt').one('click', function () { confirmThis(); $('#closeAlert').one('click').click(); });
};
if (denyThis == '') {
$('#denyIt').one('click', function () { $('#closeAlert').one('click').click(); $('#signIt').unbind(); });
} else {
$('#denyIt').one('click', function () { denyThis(); $('#closeAlert').one('click').click(); $('#signIt').unbind(); });
};
if (type == "confirm") {
$('.closeAlert, .signItForm').hide();
};
if (type == "alert") {
$('.alertConfirm, .signItForm').hide();
};
if (type == "fixedAlert") {
$('.closeAlert, .alertConfirm, .signItForm').hide();
};
if (type == "security") {
$('.signItForm').show();
$('.closeAlert').hide();
$('#confirmIt').hide();
$('#signIt').unbind().fadeTo('fast',1);
};
};
$('#signIt').live('click', function () {
var formData = (JSON.stringify($('.secureSign').serializeObject()));
var signitPwd = $('#signItpwd').val();
var jsonURL = "/jsonout/getdata.aspx?sql=SELECT id, password FROM users WHERE password ='" + signitPwd + "' LIMIT 1&output=json&usedb=new&labelName=any&fileName=";
$.getJSON(jsonURL, function (data) {
if (data.length > 0) {
$('.savingUserID').val(data[0].id);
$('#confirmIt').one('click').click();
$('#signIt').fadeTo('fast', 0);
$('#confirmIt').show();
} else {
$('#signIt').fadeTo('fast', 0);
$('#confirmIt').one('click').show();
$('.closeAlert').show();
$('.alertConfirm, .signItForm').hide();
$('#alertTitle').html("Error!");
$('#alertContent').css({ 'text-align': 'center' }).html("Password Denied");
};
});
});
From my understanding of $.one, it merely runs the event ONCE. If you bind it twice to the event, it will run twice instantaneously, but no more.
Example: http://jsfiddle.net/qCwMH/ (click the button, and it will run the event 4 times).
Each time you click saveDelivery, you are infact, binding another $.one event to #confirmIt.
What you could do is unbind your events from confirmIt and denyIt at the start of the modal function (i.e. $('#confirmIt, #denyIt').unbind('click');, and then you will assign them fresh each time that function is called, rather than building on top of them. Not ideal, as binding/unbinding uses more resources than other options, but just give that a try to start with perhaps?
I have this html form
<form action="upload/" id="upload" name="upload">
// other form data
</form>
and this in html on page where i can switch form attributes
Download
Upload
and my javascript
$("#startUpload").click(function( {
$("form").attr('action','upload/').attr('id','upload');
});
$("#startDownload").click(function( {
$("form").attr('action','download/').attr('id','download');
});
$(function() {
$('#upload').uploadThis({
// other code here
});
$(function() {
$('#download').downloadThis({
// other code here
});
my problem is when i click on href #startUpload this is attached with $('#upload').uploadThis({}) function and it works but when i click on #startDownload it is not attaching this $('#upload').downloadThis({}) function and not getting called.
thanks for any help.
I'm not sure exactly what is the wanted behavior but changing IDs of elements always brings the same sort of issues.
You are doing this:
$(function() {
$('#upload').uploadThis({
// other code here
});
});
$(function() {
$('#download').downloadThis({
// other code here
});
});
$(<Function>); is a shorthand for $(document).ready(<Function>);
The thing is that when you're document is ready, it will execute both your handlers above but at that time, only an element with ID #upload exists, $('#download') will actually be an empty selection.
What you could do is call $('#upload').uploadThis() and $('#download').downloadThis() in your respective .click() handlers after changing the IDs.
$("#startUpload").click(function( {
$("form")
.attr({ 'action': 'upload/', 'id': 'upload' })
.uploadThis(...);
});
Note: if those are plugins you wrote yourself, be sure that they won't initialize each time you call them.
Hope I'm clear enough :o)
You can do this as many times as you like:
$("#startDownload").bind('click', function() {
...
});
You are trying to bind elements before they exist on DOM... will never work.
$("#startUpload").click(function( {
$("form").attr('action','upload/').attr('id','upload').submit(function() {
$(this).uploadThis({
//other code here
});
);
});
$("#startDownload").click(function( {
$("form").attr('action','download/').attr('id','download').submit(function() {
$(this).downloadThis({
//other code here
});
);
});
THis way you will bind the action you want in the submit form event. Probably will fix your problem.
A simple approach would be to make custom events for the form and trigger them by the onclick's:
$("#startUpload").click(function( {
$("form").trigger('upload');
});
$("#startDownload").click(function( {
$("form").trigger('download');
});
$("form").bind('upload',function(){
$(this).attr('action','upload/').uploadThis();
}).bind('download',function(){
$(this).attr('action','download/').downloadThis();
});
I have a single html page with multiple div elements on it. Each time a user clicks on on a div, it is replaced with an CKEditor on the fly:
$('.editable').click(function() {
editor = CKEDITOR.replace(this);
});
Now, if the CKEditor instance loses its focus (blur event), I need to post the content to a separate script via ajax (if something changed) and destroy this instance:
$('.editable').click(function() {
editor = CKEDITOR.replace(this);
editor.on('blur', function(e)
{
if (e.editor.checkDirty())
// get data with e.editor.getData() and do some ajax magic
e.editor.destroy();
});
});
But this example won't work because, I don't know why, destory() will be called before checkDirty(). How can I get this working?
How about if you put the destroy() inside the if() statement? You could have an else clause that invokes destroy if nothing has changed. If something has changed, you can invoke destroy() within the if clause once the data has been transfered.
$('.editable').click(function() {
editor = CKEDITOR.replace(this);
editor.on('blur', function(e)
{
if (e.editor.checkDirty()) {
// get data with e.editor.getData() and do some ajax magic
if ( dataTransferComplete ) {
e.editor.destroy();
}
} else {
e.editor.destroy();
}
});
});
Or you could check a variable before invoking destroy(). Set that variable to true after the data transfer has been completed and in the else clause, that way destroy() won't be invoked until you've checked for changes and transfered any updated data.
$('.editable').click(function() {
editor = CKEDITOR.replace(this);
editor.on('blur', function(e)
{
var okToDestroy = false;
if (e.editor.checkDirty()) {
// get data with e.editor.getData() and do some ajax magic
okToDestroy = true;
} else {
okToDestroy = true;
}
if (okToDestroy )
e.editor.destroy();
});
});
This is an outline, I haven't tested the code, but if shows the concept.
Be Well,
Joe
I am using the following code to add a button to a page
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
I am then creating an Ajax Upload instance on the button.
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
What I want to do is append the button to the page then simulate clicking it automatically. How would I go about doing this?
Update
The code now reads:
$("#myDiv").html("<button id='fileUpload'>Upload</button>");
var button = $('#fileUpload'), interval;
new AjaxUpload(button, {
action: '/upload.ashx',
name: 'myfile',
onSubmit: function(file, ext) {
button.text('Uploading');
this.disable();
// Uploding -> Uploading. -> Uploading...
interval = window.setInterval(function() {
var text = button.text();
if (text.length < 13) {
button.text(text + '.');
} else {
button.text('Uploading');
}
}, 200);
},
onComplete: function(file, response) {
button.text('Upload');
window.clearInterval(interval);
}
});
$('#fileUpload').click();
The .click event does not seem to fire. It is reached in the code but does nothing...
** Update **
$('#fileUpload').click();
needs to be
$('input').click();
Please check the accepted answer for why.
What I want to do is append the button
to the page then simulate clicking it
automatically. How would I go about
doing this?
The short answer is that you don't.
The long answer:
First you need to understand how AJAX Upload works.
Plugin creates invisible file input on
top of the button you provide, so when
user clicks on your button the normal
file selection window is shown. And
after user selects a file, plugin
submits form that contains file input
to an iframe. So it isn’t true ajax
upload, but brings same user
experience.
There are two things here:
fileUpload is not the actual file input
Generally, <input type="file"> element cannot be clicked/set programmatically in modern browsers for security reasons.
You don't actually have a click handler on the button, hence nothing happens.
Simply by going
$('#fileUpload').click();
You can call the click handler on the button like this:
$('#fileUpload').click();
You have already handled adding it to the page.
$('body').append('Go').find('#send').click();