First thing is forget id’s. Since an id should be unique on the page, there is no way to handle multiple elements with the same id, as you are doing in the line function:
var element = document.getElementById("blurName");
And on the line:
if($("#firstName").val() == ''){
What you need to do is send the element as a parameter to the function this
, and there in the function take the next input element that called the function and add or remove the class .d-block
. The method .nextElementSibling
selects the adjacent element (adjacent: coming soon after). The code is extremely simple and short.
Although you are using Bootstrap with jQuery, you don’t even need to use jQuery for this, see:
function verificarForm(e){
e.nextElementSibling.classList[!e.value ? 'add' : 'remove']("d-block");
}
.invalid-feedback{
display: none;
}
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<div class="col-md-6 mb-3">
<label for="firstName">Nome</label>
<input type="text" onblur="verificarForm(this)" class="form-control" placeholder="" value="" required="">
<div class="invalid-feedback">
Digite um nome válido.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="firstName">Nome</label>
<input type="text" onblur="verificarForm(this)" class="form-control" placeholder="" value="" required="">
<div class="invalid-feedback">
Digite um nome válido.
</div>
</div>
Here: !e.value ? 'add' : 'remove'
I used a ternary operator who will select one of the two methods (add
or remove
) according to the value of the input (!e.value
).
The !e.value
returns true
if the field is empty and calls the method add
, otherwise will call the method remove
.
You can even use the .trim()
to prevent the user from only entering spaces in the input and being considered valid, since spaces are also characters:
!e.value.trim()
With jQuery the function would look like this:
function verificarForm(e){
$(e).next()[!e.value ? 'addClass' : 'removeClass']("d-block");
}
The .next()
jQuery has similar function to jQuery .nextElementSibling
.