Baltrek
Baltrek

Reputation: 97

jquery get whole option selected in html

Is there possibility to get all html option from selected dropdown. While i have

<select class="myselect">
  <option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
  <option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>

I would like to get whole option which is:

<option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>

As far i as tried i can get all options in html by:

$('.myselect').html()

Or just one data by :

$('.myselect').find(':selected').data('one')

Or just one value

$('.myselect').find(':selected').val()

So is there simple way to get selected whole html option from < option >... to < /option>

Upvotes: 0

Views: 37

Answers (2)

ADyson
ADyson

Reputation: 62074

I wasn't quite clear precisely what result you wanted, so here are a couple of ideas to get things you may be interested in:

1) To get the names and values of all the data-attributes you can just call .data() without any arguments and it will return all the data-attributes and their values in an object. There's also an example in the documentation.

2) To get the whole HTML of the selected item you can use outerHTML on the DOM element found by jQuery.

Demo of each below:

//to get the data-attributes
var selectedData = $('.myselect').find(':selected').data();
console.log(selectedData);

//to get the HTML of the selected item:
var selected = $('.myselect').find(':selected')[0].outerHTML;
console.log(selected);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
  <option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
  <option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178413

Like this - it is not clear if you want the tag or the data attributes so here are either

$(".myselect").on("change",function() {
  console.log(this.options[this.selectedIndex]); // complete tag
  console.log(this.options[this.selectedIndex].dataset); // array of data attribute values
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="myselect">
  <option value="">Please select</option>
  <option data-one="11" data-two="11" data-three="111" value="1">Some text here</option>
  <option data-one="22" data-two="22" data-three="222" value="2">Some text here2</option>
</select>

Upvotes: 2

Related Questions