0

$('.sela > option').on('click', function() {
  console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sela'>
  <option>lorem</option>
  <option>ipsum</option>
</select>

So click on lorem should set lorem, click on ipsum should set ipsum in console, regardless whether option is changed or not.

Is it possible?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • You just need to provide a ‘value’ attribute to the options and it will automatically set the value of the select. If you want to tap into what was selected then you can just listen for the ‘change’ event in the select itself. – dnak Dec 18 '18 at 16:48
  • @YongQuan and @dnak, I don't need `change` event, but `click` on an option – qadenza Dec 18 '18 at 16:50
  • @Rory McCrossan, there is no answer on your link. Just tryings. – qadenza Dec 18 '18 at 17:10
  • https://stackoverflow.com/a/21242857/519413 That is as close as you're going to get to what you require as you're attempting to use a standard control in an improper manner. If you want this behaviour *exactly* then you will need to roll your own custom control, or hack around something like Select2 – Rory McCrossan Dec 18 '18 at 17:15
  • @RoryMcCrossan, so your comment is the answer, and not the linked posts . – qadenza Dec 18 '18 at 17:28

2 Answers2

1

You could try waiting for a change to the element, then using console.log to display the value.

$('.sela').on('change', function(){
  var $this = $(this),
      $value = $this.val();

  console.log($value);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sela'>
<option>lorem</option>
<option>ipsum</option>
</select>
Sam Johnson
  • 742
  • 1
  • 8
  • 24
0

Of course it is possible, but I would first generate the value in every option and then you can simply select it with jQuery :

$('.sela option[value="1"]')

if you don't have values yet, you'll need to identify each option, the easiest way to do is to increment a counter. Or to use the option's text if you are 100% sure you won't have the same using $(".sela option[value="1"]").text() or $(this).find("option:selected").text();

If you don't even know how to add an option, loop over the select and replace every option :)

EDIT :

var allOptions = $('.sela')[0];

for(var i=0; i < allOptions.length; i++) {
    console.log(allOptions[i].value);
    allOptions[i].option = new Option('My option', 'i');
}
andrea06590
  • 1,259
  • 3
  • 10
  • 22