How to get attributes from an option field with jQuery

5

I have the following code:

<select name='exemplo' id='exemplo'>
    <option value='1' class='teste' dado='a'>1</option>
    <option value='2' class='teste' dado='b'>4</option>
    <option value='3' class='teste' dado='c'>3</option>
    <option value='4' class='teste' dado='d'>2</option>
</select>

I know that to get value of option I can use:

$('#exemplo').change(function(){
    var valor=$(this).val();
)};

But what about getting the dado attribute? How do you do?

    
asked by anonymous 10.08.2016 / 16:48

1 answer

8

You can use this way: var dado = $(this).find(':selected').attr('dado');

.find() looks for descending elements, and :selected ensures that you only choose the selected . Then using .attr() you can get this attribute dado .

$('#exemplo').change(function() {
    var valor = this.value;
    var dado = $(this).find(':selected').attr('dado');
    console.log(valor, dado);
});

jsFiddle: link

It would be more correct to use data- fields because it was agreed that this would be better. In this case in HTML you would have data-dado='a' and the whole code would look like this: link

You could also do this without jQuery ...

In this case JavaScript would look like this:

var select = document.getElementById('exemplo');
select.addEventListener('change', function() {
    var valor = this.value;
    var dado = this.querySelector('option:checked').dataset.dado;
    console.log(valor, dado);
});

jsFiddle: link

    
10.08.2016 / 16:51