0
I have a page with several <input>
and some of them are mandatory, these <input>
are not in a tag <form>
, therefore, I believe that the required
cannot work in this situation. I have done the check in hand same:
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 would like to know if it is possible to create a kind of attribute for me to put in <input>
to make this check, being as follows:
So far:
<input type="text" class="form-control" name="iptCodBarras">
After the creation of the attribute:
<input type="text" class="form-control" name="iptCodBarras" needed="true">
My intention would be to put the "attribute" needed="true"
us <input>
that I would like to be obligatory.
Answer:
I followed Marcel Felipe’s reply and got exactly what I needed, I took advantage of the beginning each
that he mentions 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>
who have the attribute needed="true"
if they are filled in, if any are not filled in, will increment the variable emBranco
and show the toastr
error, if all are filled, the variable will continue with the value 0 and execute the desired action. The <inputs>
that are blank, will be left with the reddish edge (similar to the required
) and when the user clicks on these <inputs>
blank, remove the reddish border.
Possible duplicate of Custom HTML attributes
– NoobSaibot
data-needed
is indicated by the official documentation as well as is in the response linked by @Noobsaibot– Isac
@Noobsaibot The idea of
data-*
is excellent and very welcome, but Marcel’s answer perfectly solved my question and even recorded here at Stackoverflow a technique that I believe are not all who know. Maybe my question can be duplicate, but I was successful and still a new knowledge, I think validates the permanence of the question for learning of other people who pass by.– D. Watson
@J.Thatcher Duplicate does not mean it has to be removed. The question even as duplicate must remain because it is often another entry point to get to the same problem. Another way to get to the same problem by Google search. What the duplicate indicates is that the answers should not be repeated because they are the same!
– Isac