事件没有用jQuery选择单个select2

时间:2018-04-03 18:15:50

标签: jquery ajax jquery-select2 codepen

我有一个带有两个select语句的表单,一个是select select,另一个是select select。需要获取最后一个选定项的值,以便我可以进行ajax调用以填充另一个表单。我创建了一个简单的示例,它几乎直接来自他们的文档,但它不起作用。见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");
});

1 个答案:

答案 0 :(得分:0)

在这里,如果没有选择任何内容,还会添加一些检查。如果需要,可帮助重置其他select

&#13;
&#13;
// 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);
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;