10

I'm new to jquery and javascript, so maybe this is a silly question but i'm having problems setting the value obtained from a selected option in select2 to a text input. This is my code:

  <head>

    <!-- stylesheets -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">


    <!-- scripts -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

    <script>
      $(function(){
        // turn the element to select2 select style
        $('.select2').select2({
          placeholder: "Select a state"
        });

        var data = $(".select2 option:selected").text();
        $("#test").val(data);
      });



    </script>
  </head>

  <body>

    <p>select2 select box:</p>
    <p>
      <select  class="select2" style="width:300px">
          <option> </option>
          <option value="AL">Alabama</option>
          <option value="VT">Vermont</option>
          <option value="VA">Virginia</option>
          <option value="WV">West Virginia</option>
      </select>
    </p>

    <input type="text" id="test"> 

  </body>

  </html>

Any ideas of what i'm doing wrong?

Thanks!

neek05
  • 187
  • 1
  • 2
  • 9

6 Answers6

39

You are almost there. Put your value assignments within the change handler of the dropdown. The way you have it, it's just getting called when the page is loaded.

  $(function(){
    // turn the element to select2 select style
    $('.select2').select2({
      placeholder: "Select a state"
    });

    $('.select2').on('change', function() {
      var data = $(".select2 option:selected").text();
      $("#test").val(data);
    })
  });
Matt Spinks
  • 5,382
  • 1
  • 18
  • 39
  • What about initial selection? On change/select2:select events are not firing on it. initSelection was deprecated and now referenced to some data adapter... – Alexander M. Oct 06 '19 at 19:17
15

As per the docs https://select2.org/programmatic-control/events#event-data

$('.select2').on('select2:select', function (e) {
    var data = e.params.data;
    $('#test').val(data.text);
});
robmcvey
  • 735
  • 7
  • 18
4

You can use change event: whenever an option is selected the value can be copied to the text box:

$(function(){
  // turn the element to select2 select style
  $('.select2').select2({
    placeholder: "Select a state"
  }).on('change', function(e) {
    var data = $(".select2 option:selected").text();
    $("#test").val(data);
  });

});
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<p>select2 select box:</p>
<p>
    <select  class="select2" style="width:300px">
        <option> </option>
        <option value="AL">Alabama</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WV">West Virginia</option>
    </select>
</p>

<input type="text" id="test">
gaetanoM
  • 39,803
  • 6
  • 34
  • 52
1

simply you can do this:

$('#your-select-id').on("change", function(e) {
                console.log($("#your-select-id").val())
 });
Mortada Jafar
  • 3,141
  • 1
  • 12
  • 29
0
$("#e15").on("change", function () {
    $("#e15_val").html($("#e15").val());
});
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
  • 1
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/206345) by showing _why_ this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – Suraj Rao Feb 25 '19 at 09:55
0

I am adding this here because, a couple of months back, the answers provided here worked for me, but now, some voodoo happened and the only way for me to get the value of a selected item was doing the following:

$('.findUser').select2({
    minimumInputLength: 3,
    placeholder: "Search Members...",
    allowClear: true,
    dropdownAutoWidth : true,
    width: '250px'
}).on('change', function (e) {
    console.log(e.val);
});

As you can see, I used e.val to get the value. The only way I could get the trigger of the selected value to work was using change since using select2:select simply would not work (Which it did a couple of months back if I reckon). To debug and get to this point I had to do a console.log(e) to get all events when it triggered the on change case. I also saw that you could use e.added.text to get the text of the option and e.added.id to get the id, which is similar to e.val mentioned previously.

In case you need to test e.vale agains a condition, make sure to turn it into a string or numeric. Like this:

var newValue = (e.val).toString();

This way we can make sure that, if the value is empty (false) it will return false properly in a condition and if it has any value in it, it will return true as it should. The reason is that if I leave it as an object, it will always be true. Also this method works flawlessly with multiple selected options, just by adding the parameter multiple="multiple" to the select tag.

This was tested (Surprisingly) with Select2 4.0.8, Select2 3.5.2 and Select2 3.5.3 and it ended up working. Again I am pretty sure the other answers here worked, but now I had to resort to this trickery to get it to work (After 2 hours figuring out why it did not).

Luis Alvarado
  • 7,657
  • 12
  • 46
  • 56