I am getting the below json response from an validation api , the first attribute is the id of each input field with the error message.
{
"backgroundcolor": "Color is not Supported",
"terms" : "Sorry the Terms are blank"
}
I am using jquery and bootstrap and want to append the below html just after each input field of that specific id . Is this possible to add div dynamically ?
<div id="backgroundcolor" class="invalid-feedback">
Color is not Supported
</div>
Before :
<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
</div>
After :
<div class="col-md-6">
<input type="text" class="form-control is-invalid" id="backgroundcolor" aria-describedby="validationServer03Feedback" required>
<div id="backgroundcolorFeedBack" class="invalid-feedback">
Color is not Supported.
</div>
JavaScript alone is the best and fastest solution, so here it is how i would do it:
let response = JSON.parse(response);
let fragment = document.createDocumentFragment()
let child = document.createElement('div');
child.id = Object.keys(response)[0] + 'FeedBack';
child.className = 'invalid-feedback';
child.innerText = Object.values(response)[0];
fragment.appendChild(child);
document.getElementById(Object.keys(response)[0]).after(fragment);
I hope it'll help.
Note: createDocumentFragment() may be slightly faster than createElement alone, but it's not required.
Edit: you can also check if there is already div with that error, it would prevent duplication of divs
if(!document.getElementById(Object.keys(response)[0].length) {
// Here goes code from above
}