Wednesday, 18 September 2013

JQuery $(this) is undefined in .each()

JQuery $(this) is undefined in .each()

Here is a function that take a divs id and an array of fields inside that
div.
Exemple:
section="div1",
fields=JSON.stringify({txtFNoneExp:$('#txtFNoneExp').val(),
txtFNoneDate:$('#txtFNoneDate').val()})
The function send those over to the server VIA AJAX:
function AJAXValidation(section, fields)
{
var request = $.ajax(
{
url: "ProcessJRT.php",
type: "POST",
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
data:
{
validate:section,
array:fields
}
});
request.done(
function(message)
{
var div = document.createElement('div');
//create a separate document to append message
$(div).html(message);
//Append message
$('#' + section + " .AJAXValidate").attr('title', '');
//find the fields that has the class AJAXValidate
//and reset there title attribute to ''
$(".AJAXValidate").removeClass('AJAXValidate');
//remove the class
$(div).children().each
(
//for each divs in the second document
function(i)
{
//HERE is the problem
//If I log $(div).children() I can see what is inside
//But I do the log below $(this) is undefined.
//Here is my question: Why is it undefined?
console.log($(this));
$('#' + $(this).attr('name')).attr('title', $(this).html());
$('#' + $(this).attr('name')).addClass('AJAXValidate');
}
);
if($('#'+section+' .AJAXValidate').length > 0)
{
$('#'+section+' input[type="submit"]').attr('disabled', true);
}
else
{
$('#'+section+' input[type=submit]').attr('disabled', false);
}
});
}
And than the server send back message that might contains multiple divs
like this:
<div name='txtFNoneExp'>This is a test. </div>
...
If you checked out the code you'll see that my code work fine exepte that
the $(this) in the .each(); is undefined.
A call this function else where in my page and it work just fine!
Thanks!

No comments:

Post a Comment