Reputation: 255
I have made this simple jquery script to check forms for me...
$(document).ready(function() {
$('.loading').hide();
});
function check_username(){
var username = $("#username").val();
$('.loading').show();
$.post("ajax.php", {
username: $('#username').val(),
}, function(response){
$('.info').fadeOut();
$('.loading').hide();
setTimeout("finishAjax('info', '"+escape(response)+"')", 450);
});
return false;
}
function check_email(){
var email = $("#email").val();
$('.loading').show();
$.post("ajax.php", {
email: $('#email').val(),
}, function(response){
$('.info').fadeOut();
$('.loading').hide();
setTimeout("finishAjax('info', '"+escape(response)+"')", 450);
});
return false;
}
function finishAjax(id, response){
$('.'+id).html(unescape(response));
$('.'+id).fadeIn(1000);
}
Only thing is when there is an error on the post username the error displays in all the error boxes and not the one assigned to username, anyway to stop this without assigning ids to all the divs for use of practicality.
Upvotes: 0
Views: 272
Reputation: 4139
What's wrong with setting IDs for the divs? Using jQuery you should probably use IDs as often as you can instead of classes due to the better performance.
If you absolutely do not want to do that, there are other ways to access nodes in the DOM. For example if you have some HTML-structure like
<input type="text" id="username" />
<div class="info">The error message for username.</div>
You could simply do $('#username').next()
to access the div, without using it's class name.
Upvotes: 1
Reputation: 284836
If you're using .
, that's a class selector not an id. You should not use strings when calling setTimeout
. Do;
setTimeout(function()
{
finishAjax('info', response);
}, 450);
That eliminates the need for escaping. However, it is not clear why you're using setTimeout
at all.
For your actual question, you can use after
instead of setting up a separate element. And pass the actual id of the form element:
E.g.
finishAjax('username', response);
function finishAjax(id, response){
$('#'+id).after(response).fadeIn(1000);
}
You can hide loading initially with CSS:
.loading
{
display: none;
}
instead of your ready
block.
Since you're using jQuery, you may want to look into the jQuery Validate plugin.
Upvotes: 2