Danny G Smith
Danny G Smith

Reputation: 1

event not selecting single select2 with jQuery

I have a form with two select statements, one a multi select and a single select both using select2. The need to get the value of the last selected item so I can make an ajax call to populate the other form. I have created a simple example that is almost straight out of their documentation, and it does not work. See here https://codepen.io/riskiii/pen/ZxjLJY

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<form class="signup-form-container" method="post" id="roles-form" name="roles-form">
  <select class="js-example-basic-single" name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
</form>

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
  $(".js-example-basic-single").select2();
});

$(".js-example-basic-single").on("select2:select", function(e) {
  var data = e.params.data;
  console.log(data);
  alert("hello");
});

Upvotes: 0

Views: 659

Answers (1)

Cesar Bielich
Cesar Bielich

Reputation: 4945

Here you go, also added some checking if nothing was selected. Helps to reset your other select if need be.

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
  $(".js-example-basic-single").select2();
  $(".js-example-basic-single").on("change", function(e) {
    var data = $(this).val();
    if (data == 0) {
    alert("nothing selected");
    } else {
    console.log(data);
    alert(data);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<form class="signup-form-container" method="post" id="roles-form" name="roles-form">
  <select class="js-example-basic-single" name="state">
  <option value="0">pick one</option>
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
</form>

Upvotes: 0

Related Questions