Search code examples
phpjquerylaravellaravel-blade

Checking null in jQuery


In Laravel blade I have a button that if record is not empty, it calls a JQuery function

@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

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}`)
}

}

The function works good except when the record is empty I get error

Attempt to read min_value on null

I checked the variable $first_step_validation and found it null, so why the function was called from the first place?

Also if I change the variables in the function from

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

To

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

The error goes away, but I get console error

function $first_step_validation is not defined

What I'm doing wrong? Please help!


Solution

  • $first_step_validation is null when the data is empty. you should call your function only when $first_step_validation is not null

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