Adding multiple span elements to a div

Adding multiple span elements to a div

Good afternoon, apologies for what may seem like a trivial question.

I can't seem to wrap my brain around something I am trying to accomplish. I feel it is something straightforward that I am missing.

I am trying to add multiple spans to a error div so that when an input is made and the field has lost focus, I can remove the span that showed the error to begin with.

  1. $('.required').val('');
  2. $('#insert').on('click', function()
  3. {
  4. var valid = true;
  5. msg = '';
  6. sp = '';

  7. $('.required').each(function() 
  8. {
  9. var reqs = $(this);
  10. reqd = reqs.attr('name');

  11. if (!reqs.val()) 
  12. {
  13. valid = false;

  14. if (reqd == 'username')
  15. {
  16. reqdfn = 'ID'
  17. }
  18. else if (reqd == 'lastname')
  19. {
  20. reqdfn = 'Last Name'
  21. }
  22. else if (reqd == 'firstname')
  23. {
  24. reqdfn = 'First Name'
  25. }
  26. else if (reqd == 'country')
  27. {
  28. reqdfn = 'Country'
  29. }

  30. msg += reqdfn + ' cannot be blank. <br/>';
  31. reqs.css({'border': '1px solid #C33', 'background-color': '#F6CBCA'});
  32. }
  33. });

  34. if (!valid)
  35. {
  36. //$('#error').html('');
  37. $('#error').slideDown();
  38. $('#error').append('<span class="' + reqd + '">' + msg + '<span>');
  39. }
  40. else
  41. {
  42. alert('Submitted');
  43. }
  44. });


There is a fiddle for it here

When I looked at Firebug and logged the value of reqd it was showing up as the last reqd in use.

I tried sp += reqd and obviously this gave me a value of all reqd's together as I did expect.

I am just stumped as to where I am going wrong.

Any pointers would be greatly appreciated.

Thanks.

As an aside, I tried putting the error append in the !valid check

 
when I try it this way, I am getting multiple spans in the div as follows: ID, ID + Firstname, ID + First Name + Last Name, ID + First Name + Last Name + Country. It seems to just be iterating through each one and shoving it in there as a span. Not quite sure where i'm going wrong.

The updated fiddle can be found here