Pick data-attribute from a selected option by clicking on button

Asked

Viewed 2,173 times

0

I wish that by clicking the button I could pull the value and data-dado of the selected option.

I tried with the code below, but it didn’t work:

$("#botaoexemplo").on("click", function() {
    var valor = $('#exemplo').val();
    var dado = $('#exemplo').attr(dado);
    console.log(valor, dado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name='exemplo' id='exemplo' clas="exemplo">
  <option value='1' class='teste' data-dado='a'>1</option>
  <option value='2' class='teste' data-dado='b'>4</option>
  <option value='3' class='teste' data-dado='c'>3</option>
  <option value='4' class='teste' data-dado='d'>2</option>
</select>
<button id="botaoexemplo">Teste</button>

2 answers

3


You need to add the :selected to identify the selected option and you can use the method data() to return the attribute value, if you want to recover by attr() would need to enter the full name, in the case of 'date-given'.

Simple as that:

$("#botaoexemplo").on("click", function() {
        var valor = $('#exemplo').val();
        var dado = $('#exemplo :selected').data('dado');
        console.log(valor, dado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='exemplo' id='exemplo' clas="exemplo">
        <option value='1' class='teste' data-dado='a'>1</option>
        <option value='2' class='teste' data-dado='b'>4</option>
        <option value='3' class='teste' data-dado='c'>3</option>
        <option value='4' class='teste' data-dado='d'>2</option>
    </select>
<button id="botaoexemplo">Teste</button>

1

is very simple, I always like to use $("#field option:Selected") and to take another attribute from the option use . attr("attribute").

$(function() {
      $("#botao").on("click", function() {
          var valor = $('#exemplo option:selected').val();
          var dado = $('#exemplo option:selected').attr('data-dado');
          console.log(valor, dado);
      });
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name='exemplo' id='exemplo' class="exemplo">
    <option value='1' data-dado='a'>1</option>
    <option value='2' data-dado='b'>4</option>
    <option value='3' data-dado='c'>3</option>
    <option value='4' data-dado='d'>2</option>
</select>
<button id="botao">Teste</button>

Browser other questions tagged

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