Search code examples
jquerydynamicselectorelementtargeting

Jquery: Targeting dynamically loaded HTML elements


I've been racking by brains trying to figure out why jQuery wasn't responding. But I've figured out why it's because my form below is dynamically created by javascript and not inside DOM.

If I use $(this).css("border", "1px solid red"); to target the input text field, it works and has an effect but when I use the next() it seems to not find it, I think because it's dynamic HTML.

How do I target element?

<!-- Pretend this modal box is empty. The <form> is dynamically loaded when a button is clicked -->
<div id="modal_box">
    <form id="form_a">
        <input type="text"><b></b>
        <input type="text" class="required"><b></b>
        <input type="text"><b></b>
        <br>
        <button onclick="validate('form_a')"> Go </button>
    </form>
</div>

<script>
function validate(whichform) {
    var valid = true;

    // whichform is the id so use id selector here
    $('#' + whichform + " .required").each(function (i) { 
        if ($(this).val().length == 0) {
            $(this).css("border", "1px solid red");
            $(this).next("b").html("Required field");// should I be using next()? or something else to find dynamically loaded HTML elements?
            valid = false
        }
        else {
            $(this).css("border", "1px solid black");
            $(this).next("b").html("");
        }
    });

    // Return the valid state
    return valid;
}
</script>

Solution

  • I honestly don't know why it's not working. I've tried all your examples but no luck. Instead I've had to do a little work around.

    $(this).nextAll("b").eq(0).html("Required field");
    

    And it works now.

    Thank you guys for trying to help me.