I have a page with several <input>
and some of them are required, these <input>
are not in a <form>
tag, so I think required
can not work in this situation. I have done the verification in the same hand:
if(codBarras == null || codBarras == '')
toastr.error('O Código de Barras é obrigatório!');
else if(dataVencimento == null || dataVencimento == '')
toastr.error('A Data de Vencimento é obrigatório!');
else
console.log('Faça algo!');
However, I'd like to know if it's possible to create a kind of attribute for me to put in <input>
to do this check, going like this:
So far:
<input type="text" class="form-control" name="iptCodBarras">
After attribute creation:
<input type="text" class="form-control" name="iptCodBarras" needed="true">
My intention would be to put the "attribute" needed="true"
on the <input>
that I would like to be required.
Answer:
I followed Marcel Felipe's answer and got exactly what I needed, I took advantage of the each
start he mentioned in the answer and created the following block:
var emBranco = 0;
$("[needed=true]").each(function(){
if($(this).val() == '' || $(this).val() == null)
{
emBranco++;
toastr.error('Existem campos obrigatórios em branco!');
$(this).css({'border': '1px solid salmon'});
$(this).on('focus', function(){
$(this).removeAttr('style');
});
}
});
if(emBranco == 0)
console.log('Todos os campos obrigatorios estão preenchidos!');
The previous block checks all <inputs>
that are with the needed="true"
attribute if they are filled, if any is not, it will increment the emBranco
variable and show% error%, if all are filled, the variable will continue to the value 0 and perform the desired action. The blank% will be with the reddish border (similar to toastr
) and when the user clicks on these <inputs>
blank, it will remove the reddish border.