简体   繁体   中英

Get the value of selected option in select2 and then set the value to an input text using jquery?

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>

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);
    })
  });

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);
});

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">

simply you can do this:

$('#your-select-id').on("change", function(e) {
                console.log($("#your-select-id").val())
 });
$("#e15").on("change", function () {
    $("#e15_val").html($("#e15").val());
});

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).

    $(document).ready(function() {
        //Init select2
        $('#id').select2();
        //Log selected value to console
        $('#id').on('change', function(e) {
            console.log($('#id').select2("val")); 
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM