JQuery select () method not working

I need to get data for all selected options in a select tag, and for that I used the onclick () function, which only gives data on the parameters clicked. But if the user selects all options with CTRL * A, no data will be received. I tried using select () which doesn't work 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>
      

Run codeHide result


+3


source to share


2 answers


Don't get attached to click

, but on change

. Thus, even changes resulting from other types 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>
      

Run codeHide result




As for your experiment with select

, here the documentation says:

A select event is dispatched to an element when the user makes a selection text inside. This event is limited to fields and fields.

It's just not relevant here, since the user doesn't select text, but options.

+5


source


Do it like



$('select[name=sensors]').change(function(){
    $('#demo2').text($(this).val());
});

      

+1


source







All Articles