Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select() method is not working

I need to get data for all selected options in select tag and for that I used onclick() function which gives the data of only clicked options. But if user selects all options with CTRL*A then no data will be received. I have tried to use select() which is not working in this case.

//jQuery onclick()
$('select[name=sensors]').on('click', function(){
    $('#demo').text($('select[name=sensors]').val());
});

//jQuery select()
$('select[name=sensors]').select(function(){
    $('#demo2').text($('select[name=sensors]').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type='list' name='sensors' multiple>
  <option value= "e11">e11</option>
  <option value= "e12">e12</option>
  <option value= "e13">e13</option>
  <option value= "e14">e14</option>
</select>
<!--jQuery onclick()-->
<div id="demo"></div>
<!--jQuery select()-->
<div id="demo2"></div>
like image 572
RegarBoy Avatar asked Jul 01 '26 19:07

RegarBoy


1 Answers

Don't bind on click, but on change. This way even the changes coming from other kinds of interaction will be taken into account:

$('select[name=sensors]').on('change', function(){
    $('#demo').text($('select[name=sensors]').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type='list' name='sensors' multiple>
  <option value= "e11">e11</option>
  <option value= "e12">e12</option>
  <option value= "e13">e13</option>
  <option value= "e14">e14</option>
</select>
<div id="demo"></div>

As for your experimentation with select, here's what the documentation says:

The select event is sent to an element when the user makes a text selection inside it. This event is limited to fields and boxes.

It's simply not relevant here, as the user isn't selecting text but options.

like image 196
Denys Séguret Avatar answered Jul 04 '26 08:07

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!