Catch custom data-attribute attribute within a loop

1

I want to select all custom attributes and do a validation with them, but I do not know how I can get the value of "attr" inside a loop, since they are being iterated.

HTML example:

<input type="text" data-selected="teste" value="fulano" name="nome">
<input type="text" data-selected="teste2" value="de tal" name="sobrenome">

Example:

$('[data-selected]').each(function(){

       alert( $(this).attr() ); // -> teste / teste2
});
    
asked by anonymous 09.12.2018 / 16:20

2 answers

3

Use the data() function specified in the attribute name:

$(function(){
  $('[data-selected]').each(function(){
       alert( $(this).data('selected') );
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputtype="text" data-selected="teste" value="fulano" name="nome">
<input type="text" data-selected="teste2" value="de tal" name="sobrenome">
    
09.12.2018 / 17:56
1

1) The selector should look like this: input[data-selected] . What will fetch the inputs that have the data-selected attribute defined.

  

Source: jQuery API - Has Attribute Selector

2) To receive the value of the attribute, you should inform it in the .attr() method, as suggested by the jQuery documentation. So, it should look like this: $(this).attr('data-selected'); .

  

Source: jQuery API - .attr ()

Finally , your code would look like this:

$('input[data-selected]').each(function(){
    alert( $(this).attr('data-selected') ); // -> teste / teste2
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><inputtype="text" data-selected="teste" value="fulano" name="nome">
<input type="text" data-selected="teste2" value="de tal" name="sobrenome">
    
09.12.2018 / 17:11