如何使用JS在模态节目中选择ID选项?

时间:2018-08-19 04:21:25

标签: javascript jquery ajax laravel

当模式处于显示状态时,我试图获取所选选项的ID。

$("#modal-form").on('shown.bs.modal', function(e) {
  console.log("CHANGE");
  var id = $("#customer option:selected").val();
  console.log(id);
});
<div class="form-group">
  <label for="customer" class="col-md-2 control-label">Customer</label>
  <div class="col-md-9">
    <select class="form-control" id="customer" name="customer" class="form-control">
      <option value="John">John</option>
      <option value="Alex">Alex</option>
    </select>
    <span class="help-block with-errors"> </span>
  </div>
</div>

3 个答案:

答案 0 :(得分:0)

尝试以下代码。从父级中找到元素,

$(document).on('shown.bs.modal', '#modal-form', function() {
  console.log("CHANGE");
  //var id = $("#customer>option:selected").val();
  var id = $('#customer').find(":selected").val();
  alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label for="customer" class="col-md-2 control-label">Customer</label>
  <div class="col-md-9">
  <form id="modal-form">
    <select class="form-control" id="customer" name="customer" class="form-control">
      <option value="John">John</option>
      <option value="Alex">Alex</option>
    </select>
    </form>
    <span class="help-block with-errors" </span>
  </div>
</div>

答案 1 :(得分:0)

希望这会有所帮助。

$("#customer").change(function(e) {
  alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="customer" class="col-md-2 control-label">Customer</label>
  <div class="col-md-9">
    <select class="form-control" id="customer" name="customer" class="form-control">
      <option value="John">John</option>
      <option value="Alex">Alex</option>
    </select>
    <span class="help-block with-errors" </span>
  </div>
</div>

答案 2 :(得分:0)

我发现您尚未选择任何选项,并且正在检查选择选项,选择任何一个选项并将其签出。

$("#modal-form").on('shown.bs.modal', function(e) {
  console.log("CHANGE");
  var id = $("#customer option:selected").val();
  console.log(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="customer" class="col-md-2 control-label">Customer</label>
  <div class="col-md-9">
    <select class="form-control" id="customer" name="customer" class="form-control">
      <option value="John" selected>John</option>
      <option value="Alex">Alex</option>
    </select>
    <span class="help-block with-errors"> </span>
  </div>
</div>