V. Prince V. Prince - 6 months ago 8
jQuery Question

getting the value of selected options using jquery

this is my jquery

$(document).ready(function(){
$("select.sysem").click(function(){
var selectedvalue = $(".sysem option:selected").val();
var hidden = document.getElementById('prens');
hidden.value += selectedvalue;

});
});


and this is my html code

<form method='post'>
<select id='psy' class='sysem' name='psy' multiple='true' size='5'>
<option value='s1'>Sample1</option>
<option value='s2'>Sample2</option>
<option value='s3'>Sample3</option>
</select>
<textarea id='prens' name='prens' coloumn='20' row='5'></textarea>
</form>


now my problem is when i select Sample1 then i hold the
Ctrl button
so that i can select another option, and then i select Sample2 the result in the textarea is
s1s1s1
it should be
s1s2s3
. But When i start selecting at the bottom the result is ok
s3s2s1
.

It seem's that when i start selecting at the top to bottom the result becomes redundunt and if i start selecting at the bottom to top the result is ok...

can anybody help me... im a newbie in programming..

Answer

Your selector is select instead of option, that's why you get always the first:selected value.

Try this instead

$(document).ready(function(){
  $("select.sysem option").click(function(){
    var hidden = document.getElementById('prens');
    hidden.value += this.value;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='post'>
  <select id='psy' class='sysem' name='psy' multiple='true' size='5'>
    <option value='s1'>Sample1</option>
    <option value='s2'>Sample2</option>
    <option value='s3'>Sample3</option>
  </select>
  <textarea id='prens' name='prens' coloumn='20' row='5'></textarea>
</form>

If you want to only get the selected ones:

jQuery(function($){ // DOM ready

  $("select.sysem").on("change", function(){
    var sel = $(":selected", this).map(function() {
      return this.value;
    }).get().join();
    document.getElementById('prens').value = sel;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method='post'>
  <select id='psy' class='sysem' name='psy' multiple='true' size='5'>
    <option value='s1'>Sample1</option>
    <option value='s2'>Sample2</option>
    <option value='s3'>Sample3</option>
  </select>
  <textarea id='prens' name='prens' coloumn='20' row='5'></textarea>
</form>

Comments