Lamloumi Afif Lamloumi Afif - 6 months ago 10
Javascript Question

.empty() jQuery method and undefined value

HTML:

<div class="form-group">
<div id="errorsum"></div>
</div>


JavaScript:

var errornbr = 0;
var mess;
$("#addclient input.form-control").each(function (index) {
if ($(this).val() == "") {
if ($(this).attr("data-val") != undefined) {
if ($(this).attr("data-val-required") != undefined) {
errornbr = errornbr + 1;
mess = mess + "<br/>" + $(this).attr("data-val-required");
}
}
}
});
$("#errorsum").empty();
if (errornbr > 0) {
$("#errorsum").append("<label class='col-xs-3 control-label text-danger' >" + mess + "</label>");
}


First line of the label text is always
undefined
. the
mess
didn't contains such value.

So I need to know:


  1. Does the
    empty()
    method is the reason of this?

  2. How can I fix this issue?


Answer

change var mess; to var mess = '';

Make the assume text value making it not return undefined

Comments