Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

Any ideas of what i'm doing wrong?

Thanks!

like image 915
neek05 Avatar asked Jan 28 '17 14:01

neek05


2 Answers

simply you can do this:

$('#your-select-id').on("change", function(e) {
                console.log($("#your-select-id").val())
 });
like image 111
Mortada Jafar Avatar answered Oct 09 '22 17:10

Mortada Jafar


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);
});
like image 43
robmcvey Avatar answered Oct 09 '22 16:10

robmcvey