Carlos27
Carlos27

Reputation: 185

get data-* from different selects onchange

Trying to send the value of the data-* attribute to a function.

I have two different selects and I want to send the data-addr value of the selected option to the function and display it in the #results div.

I was able to make it work with one select using the following script but I want my script to work with more than one select and to replace with the last selected option's data-addr value.

var test = $('#thefirstselect option:selected').data('addr');
$('#result').text(test);

here is the html

<div>
  <select class="form-control" id="thefirstselect" onchange="setaddress();">
    <option value="" data-addr="001">one</option>
    <option value="" data-addr="002">two</option>
    <option value="" data-addr="003">three</option>
  </select>
</div>

<div>
  <select class="form-control" id="thesecondselect" onchange="setaddress();">
    <option value="" data-addr="004">four</option>
    <option value="" data-addr="005">five</option>
    <option value="" data-addr="006">six</option>
  </select>
</div>

https://codepen.io/carlos27/pen/brQBGE

Upvotes: 2

Views: 41

Answers (1)

j08691
j08691

Reputation: 207861

Use $(this) to refer to the select being changed and option:selected to select the option that was chosen. Also avoid inline JavaScript:

$('#thefirstselect, #thesecondselect').change(function() {
  var test = $(this).find('option:selected').data('addr');
  console.log(test);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <select class="form-control" id="thefirstselect">
    <option value="" data-addr="001">one</option>
    <option value="" data-addr="002">two</option>
    <option value="" data-addr="003">three</option>
  </select>
</div>

<div>
  <select class="form-control" id="thesecondselect">
    <option value="" data-addr="004">four</option>
    <option value="" data-addr="005">five</option>
    <option value="" data-addr="006">six</option>
  </select>
</div>

Upvotes: 2

Related Questions