How to create an attribute for an HTML tag? Something similar to the existing "required"

Asked

Viewed 745 times

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.

  • 1

    Possible duplicate of Custom HTML attributes

  • data-needed is indicated by the official documentation as well as is in the response linked by @Noobsaibot

  • @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.

  • @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!

2 answers

2


You can change your DOCTYPE declaration, it would look like this:

<!ATTLIST element-name attribute-name attribute-type attribute-value>

DTD example:
<!ATTLIST input obrigatorio CDATA "true">

XML example:
<input type="text" obrigatorio="true" />

When fetching the attribute by tag javascript recognizes it:

<!ATTLIST element-name attribute-name attribute-type attribute-value>

DTD example:
<!ATTLIST input obrigatorio CDATA "true">

XML example:
<input type="text" obrigatorio="true" />

<script type="text/javascript">
	alert(document.getElementsByTagName('input')[0].getAttribute('obrigatorio'));
</script>

Using Jquery you can search all the elements that have the attribute and make a dynamic validation:

$("[obrigatorio=true]").each(function(data){
    if(!data) alert("Inválido");
});

You can read more about it at the following link: https://www.w3schools.com/xml/xml_dtd_attributes.asp

  • Every time you want to create a new attribute you have to add <!ATTLIST input nome_atributo CDATA "true"> in the code? I wonder why it’s the first time I’ve seen it.

  • That’s right. But I recommend you to check your tag attributes well before creating new ones, it may be that what you need already exists.

  • Interesting idea. I’m thinking about checking out the value of <input> that are tagged obrigatorio=true, if it is null or empty, trigger the required field message. Think it is possible?

  • Got it, I didn’t create the question. Well, it wouldn’t be easier to use data-*? As in the question marked as duplicate? Custom HTML attributes

  • Now that I just saw the link you marked in the comment, it seems better yes, this is an idea that I did not know.

  • @J.Thatcher is yes, see the Jquery code I put at the end of the answer

  • I managed to reach my goal with your answer and still learned something new, something I had never heard of. VLW!

Show 2 more comments

0

Use a classe for the mandatory inputs.

For each value-free input recover the attribute value data-id and invite them to present in a div.

1 - example without barcode and no due date

$(document).ready(function() {
   var erros = "";
	$('.obrigatorio').each(function (i, el) {
	   var data = $(el).val();
           if(data == null || data == ''){
              erros += ($(this).attr("data-id") + "<br>");
              $(this).css({'border': '1px solid salmon'});
           }
           var len = data.length;
           if (len<1) {
               $( ".error" ).html(erros);
               event.preventDefault();
               return;
           }
       });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="error"></div>

1 <input type="text" name="codBarras" value="" data-id="O Codigo de Barras é obrigatorio" class="obrigatorio">
  <br/>
2 <input type="text" name="dataVencimento" value="" data-id="A Data Vencimento é obrigatória" class="obrigatorio">
  <br/>
3 <input type="text" name="c" value="" data-id="Não obrigatorio" class="nao" placeholder="Não obrigatório">

2 - example without an expiry date

$(document).ready(function() {
   var erros = "";
	$('.obrigatorio').each(function (i, el) {
	   var data = $(el).val();
           if(data == null || data == ''){
              erros += ($(this).attr("data-id") + "<br>");
              $(this).css({'border': '1px solid salmon'});
           }
           var len = data.length;
           if (len<1) {
               $( ".error" ).html(erros);
               event.preventDefault();
               return;
           }
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="error"></div>

1 <input type="text" name="codBarras" value="2134567455676" data-id="O Codigo de Barras é obrigatorio" class="obrigatorio">
  <br/>
2 <input type="text" name="dataVencimento" value="" data-id="A Data Vencimento é obrigatória" class="obrigatorio">
  <br/>
3 <input type="text" name="c" value="" data-id="Não obrigatorio" class="nao" placeholder="Não obrigatório">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.