I have this jQuery object which I need to pull into a function, is this possible? Please see the code snippet:
var input;
jQuery('.upload').live('click', function()
{
input = jQuery(this).find(".image-path");
tb_show(title, 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.send_to_editor = function( html )
{
if (input)
{
console.log(input); // works and defined at this point...
var data {
action: "doFunction"
};
jQuery.post( ajaxurl, data, function( response )
{
console.log(input); // does not work, not defined...why??
input.val(response); // this gives me input.val(response) is not a function
});
}
}
Major edit now that the OP has disclosed their actual code:
The problem is that the value of
inputis not set until sometime later when the upload button is clicked, but you’re trying to use that value before then, thus it’s still uninitialized. You should change your code to something like this:I’m still unsure that your jQuery matches your HTML appropriately since you haven’t disclosed your HTML. Your current code is looking for an object with
class="image-path"that is a child of the clicked on button. That is a bit unusual form of HTML which makes me suspect your jQuery isn’t right for your HTML which would be another problem to fix.Original answer before the OP disclosed their actual code.
All you have to do is two things:
imageObjis defined in the proper scope so it’s available in your response callback..val()method. Since it’s generally<input>objects that have a.val()method that works and<input>objects aren’t usually container objects, I suspect this is at least part of your problem.There are two ways to make sure that
imageObjis declared in the proper scope:Like this:
To make sure that
imageObjresolves to the proper type of DOM object, you can add debugging code to first check to see ifimageObj.lengthis non-zero and then you need to make sure that the parent object(s) withclass="image-wrapper"are actually<input>objects that have a working.val()method. Since input objects usually are not container objects, this may be part of your problem. We could advise more specifically if you showed us your HTML.Here’s a working example: http://jsfiddle.net/jfriend00/EJ8yu/