我有一个带有html的select 2框:
<div class="col-md-9">
<select class="form-control select2" style="width: 100%;" id="project_status" name="project_status" data-placeholder="Select a project status">
<option value="" ></option>
<option value="Pipeline" selected>Pipeline</option>
<option value="Started">Started</option>
<option value="Closed">Closed</option>
</select>
</div>
我有这样的JS:
$("#project_status").select2({
allowClear: true
});
我想清除此字段,以防我在另一个框中选择以下选项:
$('#project_type').change(function() {
project_type_value_check();
});
function project_type_value_check() {
project_type_val = $("#project_type option:selected").val();
if (project_type_val == "Pre-sales")
{
$('#project_status').val(null).trigger('change');
}
}
但奇怪的是,这样做时,我得到非常奇怪的行为。第一次加载页面时,将调用函数project_type_value_check()并清除该值。但是,如果我将框项目类型更改为例如project,然后将项目状态设置为开始,然后再次尝试将项目类型设置为Pre-sales,则会收到错误消息:
Uncaught RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at Function.fa [as find] (jquery.min.js:2)
at n.fn.init.find (jquery.min.js:2)
at new n.fn.init (jquery.min.js:2)
at n (jquery.min.js:2)
at project_type_value_check (2019:4581)
at HTMLSelectElement.<anonymous> (2019:4626)
at HTMLSelectElement.dispatch (jquery.min.js:3)
at HTMLSelectElement.r.handle (jquery.min.js:3)
at Object.trigger
答案 0 :(得分:0)
我想将选择框设置为null会导致问题,将其更改为empty
。
$('#project_status').val(null).trigger('change');
到
$('#project_status').val('');
$('#project_status').select2().trigger('change');
$("#project_status").select2({
allowClear: true
});
$('#project_type').change(function() {
project_type_value_check();
});
function project_type_value_check() {
project_type_val = $("#project_type option:selected").val();
if (project_type_val == "Pre-sales")
{
$('#project_status').val('');
$('#project_status').select2().trigger('change');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Select2 CSS -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css">
<!-- Select2 JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js" type="text/javascript"></script>
<div class="col-md-9">
<select class="form-control select2" style="width: 100%;" id="project_status" name="project_status" data-placeholder="Select a project status">
<option value="" >--select--</option>
<option value="Pipeline" selected>Pipeline</option>
<option value="Started">Started</option>
<option value="Closed">Closed</option>
</select>
</div>
<select id="project_type">
<option value=""></option>
<option value="Pre-sales">Pre-sales</option>
</select>