JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<label for="body">Body:</label>
<input type="text" id="body"></input>
</div>
<div>
<label for="subject">Subject:</label>
<input type="text" id="subject"></input>
</div>
<div>
<button id="errorButton">Submit</button>
</div>
JavaScript
$("#errorButton").click(function() {
var errorJson = '{"body":["Please enter a body."],"subject":["Please enter a subject."]}';
var errors, messages, input, errorContainer, i, length;
// Parse the JSON into an object;
errors = $.parseJSON(errorJson);
// Iterate each key in the hash (associative array)
for (element in errors) {
// get the array of error messages for the element
messages = errors[element];
// generate the jQuery selector and get the element
input = $("#" + element);
// define a container to contain the elements error messages
errorContainer = $("<span>");
// get the length of messages for the given element
length = messages.length;
// populate the error container with all the error messages for this element
for (var i = 0; i < length; i++) {
errorContainer.append(
$("<div>").append(messages[i]));
}
// insert the error container after the input element
input.after(errorContainer);
};
});