sophiaor
sophiaor

Reputation: 11

Javascript, problem to validate value after converting Nan to 0.00

Originally, I have below javascript to validate weight. But realize there is a chance that there may be no selfDefinedGrid which means weight will be NaN. Then I added an if/else statement to convert NaN to 0.00. The conversion is working but the weight validation is no longer working. Please advise how this can be fixed such that it converts the NaN value to 0.00 and it will also perform the weight checking.

Original:

    $j( '#' + config.TableGridNames._02_SelfDefined + ' tbody tr td:nth-child(' + config.SelfDefinedGrid.Edit_Weight_Idx + ')' ).each( function ()
    {
        var row_index = $j( this ).closest( 'tr' ).index();
        /* skip over the header row; return is equivalent to continue */
        if ( row_index == 0 ) { return; }

        $j( this ).css( { 'background-color': 'white' } );
        var oWeight = $j( this ).find( 'input' );
        if ( !helper.isNumber( oWeight.val() ) || parseFloat( oWeight.val() ) < 0 || parseFloat( oWeight.val() ) > 1 )
        {
            $j( this ).css( { 'background-color': '#FFD1D1' } );
            blIsError = true;
        }

        decWeight = decWeight + parseFloat( oWeight.val() );
        console.log( 'Self-Defined (' + row_index.toString() + ') ' + decWeight.toString() );
    } );

Update:

    $j( '#' + config.TableGridNames._02_SelfDefined + ' tbody tr td:nth-child(' + config.SelfDefinedGrid.Edit_Weight_Idx + ')' ).each( function ()
    {
        var row_index = $j( this ).closest( 'tr' ).index();
        /* skip over the header row; return is equivalent to continue */
        if ( row_index == 0 ) { return; }

        $j( this ).css( { 'background-color': 'white' } );
        var oWeight = $j( this ).find( 'input' );

    if (oWeight.val() == 'NaN')
    {
    oWeight.val() = 0.00;
    }   else    {
            return oWeight.val();

        }

        if ( !helper.isNumber( oWeight.val() ) || parseFloat( oWeight.val() ) < 0 || parseFloat( oWeight.val() ) > 1 )
        {
            $j( this ).css( { 'background-color': '#FFD1D1' } );
            blIsError = true;
        }

        decWeight = decWeight + parseFloat( oWeight.val() );
        console.log( 'Self-Defined (' + row_index.toString() + ') ' + decWeight.toString() );
    } );

Upvotes: 1

Views: 54

Answers (1)

AndrewPMarks
AndrewPMarks

Reputation: 41

If looks like you are trying to assign 0.0 to a function call, and that is causing the issue.


if (oWeight.val() == 'NaN') {
    oWeight.val() = 0.0;
} else {
    return oWeight.val();
}

Here is a fix for the code above


let val = 0.0;
if (oWeight.val() == 'NaN') {
    val = 0.0;
} else {
    val = oWeight.val();
}

A more compact solution


let val = oWeight.val() == 'NaN' ? 0.0 : oWeight.val();

then, in either example, you can use val in place of oWeight.val()

Upvotes: 1

Related Questions