Mike
Mike

Reputation: 3418

How do I add dynamic content to a div generated dynamically?

Basically I am validating a form, I am collecting the error messages and I am appending them to a div generated dynamiclly. Now I am unable to append these message to this div .here is what I had done

//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'>.html(errorMsg)</div><div>`<a href='javascript:void(0);' class='cross'>X</a><div></div>");

.html(errorMsg) this causes error/is incorrect

function closeErrorBox() {
            var errorMsg = "";
                var ferrorMsg =  "Please say your first name" + "<br>";
                var aerrorMsg = "Please type address" + "<br>";
                var eerrorMsg = "Please type a valid email Address" + "<br>"
                if($("#name").val() == "") {
                    errorMsg += ferrorMsg;
                }
                if($("#address").val() == "") {
                    errorMsg += aerrorMsg;
                }
                if($("#email").val() == "") {
                    errorMsg += eerrorMsg;
                }

                $(".errorContainer").html(errorMsg);


                $(".overlay").remove();
                }

Upvotes: 0

Views: 1132

Answers (2)

mgibsonbr
mgibsonbr

Reputation: 22007

The .errorContainer div is inside the .overlay div. When you remove overlay in the end of your function, errorContainer is removed too. Other than that, it seems the .html(errorMsg) is working fine (if it still causing error, please specify what's going wrong).

Re-reading your question, I couldn't understand you program's flow: are you adding that div when the error is already known, and closing it when you click the "X"? If thats the case, I'd suggest doing something like this:

var errorMsg = "";
var ferrorMsg =  "Please say your first name" + "<br>";
var aerrorMsg = "Please type address" + "<br>";
var eerrorMsg = "Please type a valid email Address" + "<br>"
if($("#name").val() == "") {
    errorMsg += ferrorMsg;
}
if($("#address").val() == "") {
    errorMsg += aerrorMsg;
}
if($("#email").val() == "") {
    errorMsg += eerrorMsg;
}

// Adapting Diego's answer:
$("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>")
    .appendTo($("body"))
    .find(".errorContainer")
        .html(errorMsg)
        .end()
    .find(".cross")
        .click(function(e) {
            e.preventDefault();
            $(this).closest(".overlay").remove();
        });

Upvotes: 1

Diego
Diego

Reputation: 18349

I think you meant:

//generates a div onclick of submit button
$("body").append("<div class='overlay'><div class='errorContainer'></div><div><a href='javascript:void(0);' class='cross'>X</a><div></div>").find(".errorContainer").html(errorMsg);

Upvotes: 0

Related Questions