jQuery TypeError: $(...).val(...) is null



我似乎无法在代码中找到缺陷。我正在使用 select2 作为我的选择列表,右侧有一个按钮,单击该按钮时会执行以下脚本:

<script type="text/javascript">
function clearBiller() {
$('#bill_to').val('').trigger('change');
}
</script>

但是单击时,我收到引用此脚本的TypeError: $(...).val(...) is null错误:

<script>
$(document).ready(function(){
$('#bill_to').on('change', function() {
if ($(this).val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});
});
</script>

这个问题在第二个函数中的某个地方,我只是不确定如何确定它。目前,这是表单中该部分中的html:

<select id="bill_to" name="bill_to" class="js-example-basic-single form-control">
@if($shipment->bill_to)
<option value="{{$shipment->bill_to}}" selected>3</option>
@endif
@foreach($cCustomers as $customer)
<option value="{{$customer->id}}">{{$customer->customer_name}}</option>
@endforeach
</select>
<img src="/images/clear.png" height="15px" width="15px" style="margin-left: 5px;" onclick="clearBiller()">
<div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
</div>

谁能发现什么?

更新

根据下面在我的情况下效果最好的建议,我的脚本现在如下所示:

$(document).ready(function() {
if ($('.js-example-basic-single').val() == "") {
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
}
var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$('#biller').removeClass('hidden');
$('#existing_biller_details').addClass('hidden');
alert('cleared');
}
else
{
$('#biller').addClass('hidden');
$('#existing_biller_details').removeClass('hidden');
alert('not cleared');
}
});
});

上面的警报只是为了指导我解决不起作用的问题。目前,我加载了我已将 id 为"existing_biller_details"的div 设置为已经隐藏的页面,但如果在 select2 中选择一个值,则会删除"隐藏"类。

我目前的问题是使用上面的代码,只有"else"才能完全工作。如果我通过最初的"if"语句,它只会进行$('#biller').removeClass('hidden'),然后它不能再进一步了。我在控制台中没有看到任何错误,但没有出现警报,命令$('#existing_biller_details').addClass('hidden')也不起作用。

也许这对你有帮助

var $eventSelect = $("#bill_to");
$eventSelect.select2();
$eventSelect.on("select2:select", function (e) {
if ($eventSelect.select2().val() == '')
{
$("#biller").show();
}
else
{
$("#biller").hide();
}
});

您应该直接在#bill_to上触发更改事件

$('#bill_to').val('');
$('#bill_to').trigger('change');

但是您应该检查 Select2 文档,因为当 Select2 初始化并且 Select2 有自己的一组更改事件等时,您的主选择会被隐藏。

最新更新