在jQuery中检查null

8fsztsew  于 2023-10-17  发布在  jQuery
关注(0)|答案(1)|浏览(91)

在Laravel blade中,我有一个按钮,如果record不为空,它会调用JQuery函数

@if(!empty($first_step_validation))
    <button onclick="validate_first_step()" class="next action-button" type="button" name="next">(Save & Next)</button>
@else
    <button class="next action-button" type="button" name="next"> (Save & Next)</button>
@endif

jQuery函数

function validate_first_step() {

var target_value_entry = $('input[name="target_value"]').val();
var tag = {!! $workstep->subprocess_id !!} ; 

var first_step_min = {!! $first_step_validation->min_value !!} ;
var first_step_max = {!! $first_step_validation->max_value !!} ;

var first_step_target = {!! $first_step_validation->target_value !!} ;

console.log(first_step_min);
console.log(first_step_max);
console.log(first_step_target);

if(target_value_entry > first_step_min && target_value_entry < first_step_max) {
     alert('You are doing well.');
}
if(target_value_entry < first_step_min) {
     alert(`Warning! Your entry for this step is below the expected target value of: ${first_step_min}`)
}
if(target_value_entry > first_step_max) {
     alert(`Warning! Your entry for this step is above the expected target value of: ${first_step_max}`)
}

}
该函数工作正常,除了当记录为空时,我得到错误

Attempt to read min_value on null

我检查了变量$first_step_validation,发现它为null,那么为什么这个函数从一开始就被调用了呢?
同样,如果我将函数中的变量从

var first_step_min = {!! $first_step_validation->min_value !!} ;

var first_step_min = { $first_step_validation->min_value ?? ""} ;

错误消失了,但我得到console error

function $first_step_validation is not defined

我做错了什么?救命啊!

swvgeqrz

swvgeqrz1#

当数据为空时,$first_step_validation为null。你应该只在$first_step_validation不为null时调用你的函数

@unless(empty($first_step_validation))
    <script>
        function validate_first_step() {
        }
    </script>
@endunless

相关问题