JSFiddle - React, Tailwind, and code Playground

by Jiff Pom

HTML

<input data-required="true" type="text" name="foo" />
<select data-required="true" >
   <option value=""></option>
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
   <option value="mercedes">Mercedes</option>
   <option value="audi">Audi</option>
</select>

JavaScript

$("input[data-required='true']").after('<span class="label_error"></span>');

$("input[data-required='true']").focus(function() {
if ($(this).val().length <= 0) {
  $(this).siblings('.label_error').text('This field is required');
} else {
$(this).siblings('.label_error').text('');
}
}).blur(function() {
if ($(this).val().length <= 0) {
  $(this).siblings('.label_error').text('This field is required');
} else {
$(this).siblings('.label_error').text('');
}
}).change(function() {
if ($(this).val().length <= 0) {
  $(this).siblings('.label_error').text('This field is required');
} else {
$(this).siblings('.label_error').text('');
}
}).keyup(function() {
if ($(this).val().length <= 0) {
  $(this).siblings('.label_error').text('This field is required');
} else {
$(this).siblings('.label_error').text('');
}
});