Reputation: 5670
I'm using Ben Nadel's iFrame Upload function for an editing tool on a site I'm working on. I'm learning jQuery. The function works beautifully. It's part of a reuseable modal window and everything works. But, I want to dynamically tell the function where the call came from so it loads the proper form into the modal window. How would I pass that into the function. Right now it's hard coded to receive for #uploadform. Essentially, I want to re-use the function and drop in the varialbles like the action, preview and form ID etc...
$(function(){
var jForm = $( "#uploadform" );
jForm.submit(
function( objEvent ){
var jThis = $( this );
var strName = ("uploader" + (new Date()).getTime());
var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );
jFrame.css( "display", "none" );
jFrame.load(
function( objEvent ){
var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];
var jBody = $( objUploadBody );
var objData = eval( "(" + jBody.html() + ")" )
var thumb = ('thumbnails/' + eval(jBody.html()));
$("#header").css("background", "url(" + thumb + ") no-repeat center");
$("#preview").attr("src", thumb);
setTimeout(
function(){
jFrame.remove();
},100);
});
$( "body:first" ).append( jFrame );
jThis
.attr( "action", "upload_act_single.cfm" )
.attr( "method", "post" )
.attr( "enctype", "multipart/form-data" )
.attr( "encoding", "multipart/form-data" )
.attr( "target", strName );
});
});
Upvotes: 2
Views: 15407
Reputation: 349
I was going to suggest something similar except create a separate function for the occasion:
function formSubmit(formId) {
var jForm = $("#"+formId);
//remainder of your code
}
Next, for each form create your onSubmit connection either directly when declaring the html form:
<form id="myForm" class="pageForms" onsubmit="function(formSubmit(this.id))> ...
Or programatically:
$("#myForm").submit(function() {
formSubmit("#myForm");
});
[OR]
$(".pageForms").submit(function() { //to apply to all forms within the document
formSubmit("#"+this.id); //with that class
});
OR for all forms in the document (but not sure if it will work)
$("form").submit(function() {
formSubmit("#"+this.id);
});
Remember to perform the attachment in the onLoad function [$(function(){ ... })] or otherwise javascript errors could occur :S
Upvotes: 4
Reputation: 4664
var myFunction = function(formid) {
var jForm = $( formid );
// ....
}
$(function() {
myFunction("#uploadform");
});
$(function() {
myFunction("#uploadform2");
});
Upvotes: 0