How to pick attributes from an option field with jQuery

Asked

Viewed 7,321 times

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 to catch the value of option selected can use:

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

But to get the attribute dado? How do you do?

1 answer

9


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

The .find() seeks descending elements, and the :selected ensures that it only chooses the selected. Then using the .attr() you can get that attribute dado.

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

jsFiddle: https://jsfiddle.net/roc0a6pe/

It would be more correct to use fields data-, because it was agreed that this would be better. Then in HTML you would have data-dado='a' and the whole code would look like this: https://jsfiddle.net/roc0a6pe/1/

You could also do it without jQuery...

In this case Javascript would be 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: https://jsfiddle.net/roc0a6pe/3/

  • I recommend to use .bind( is better and not .change(, for reason depends on jQuery version. $('#exemplo').bind('change', function() {

  • 1

    @Kingrider the .change() was added in version 1.0. The same as the .bind()

  • 1

    Perfect!! Thank you

  • @Sergio, negative and nothing even, see about it, if the browser does not all work jquery function and follows (http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/) ... that you put the pure javascript code very good, option:checked hum did not even know... good to know, thank you!

  • @Kingrider is very useful, and already well supported: http://caniuse.com/#feat=css-sel3

  • @Kingrider I know that the live, on, bind and delegate are different, but here is the case of change which was added along with the bind in the version 1.0: https://api.jquery.com/category/version/1.0/

  • 1

    Ual, this tip has helped me so much, thanks @Sergio

Show 2 more comments

Browser other questions tagged

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