I have a form and I’m dynamically adding new input & select elements in to it via jQuery’s load function. Sometimes the loaded elements are in purpose empty and in that case I want to hide the container div so it won’t break the style.
The problem is, that I seem to be unable to count the loaded elements and therefore don’t know if it should be hidden or not.
For example I have this:
<div id="param_container"></div>
And on some dropdown menu change I have binded this function:
alert($('#param_container').children().length);
// Returns and loads new element correctly. Can be empty.
$('#param_container').load('/get_params', {cat:category});
if ($('#param_container').children().length ) {
$('#param_container').css('display', 'block');
} else {
$('#param_container').css('display', 'none');
}
alert($('#param_container').children().length);
The length of the children are always 0 even though new children element has been added.
Any thoughts?
EDIT:
My solution
$('#param_container').load('/get_params', {cat:category}, function(response) {
if (response) {
$('#param_container').css('display', 'block');
} else {
$('#param_container').css('display', 'none');
}
});
The reason is that the
loadcall is asynchronous, it completes after your function returns.You can use the success callback, like this: