我似乎找不到我的代码中的错误。我正在使用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中选择一个值,则会删除“hidden”类。
我目前的问题是,使用上述代码,只有“else”完全起作用。如果我经过最初的“if”语句,它只会执行
$('#biller').removeClass('hidden')
,然后就无法继续执行了。我在控制台中没有看到任何错误,但是没有警报弹出,也不能执行$('#existing_biller_details').addClass('hidden')
命令。