What is causing this extra "undefined"?
I've created a form and I'm using jQuery to check all fields with the "required" class. If the value for a field is empty, I'll eventually have it append an error message to an error div.
Anyway, for some reason in my testing, I'm getting an extra "undefined" when I try to output the "name" attribute to the errors div.
Here's a live example: http://lab.willpracht.net/form.php Click the button at the top.
You'll notice the extra "undefined" before the firstName. Can anyone figure out what's causing that? I'm confused as hell.
Here's the js:
$('input[type="button"]').click(function(){
var errors;
// Disable the error message, if displayed.
$('html').scrollTop(0);
$('#error').fadeOut('slow');
// Loop thru all required, check to see if empty.
$('.required').each(function(){
if($(this).val() === ''){
//errors += $(this).attr('id') + 开发者_JAVA技巧'<br />';
errors += $(this).attr('name') + '<br />';
}
});
$('#error .texture').html(errors);
$('#error').fadeIn('slow');
});
Thanks, everyone :).
try to set var errors;
to var errors="";
Define errors as a string:
var errors = "";
var errors;
just declares a variable. Declaring a variable without setting a value keeps the value at undefined
.
精彩评论