yii2:jquery if gridview column contains specific value than change color

Let's say I have a column in my grid-view is_delivered, which contains array of values of for example

(1,1,0), (1,1,1),(0,0,0) that is three combinations in all. I have set the id of the cell as 'delivered'

Now how I can changed the color of the row for example red, blue or yellow depending on the value in the column.

like for example if it is (1,1,1)then row-color will be green, if (1,1,0) then row-color will be yellow and else red.

I cannot make it out where and how to start. I cannot use here == as it can contain more than 3 values. Need to use some operator like contains.

I am trying to use a simple code like

<?php      
$script = <<<EOD
alert ($('#delivered').val());

EOD;
$this->registerJs($script);        
?>

but it is giving me a blank alert without any value.

Thanks for any suggestion.

updating question for deriving values for column is_delivered

[
             'attribute'=>'is_delivered',             
            'value' => function ($data) {
                $str = '';
                foreach($data->medicineRequests as $request) {
                    $str .= $request->is_delivered.',';
                }
                return $str;

            },

        ],

So the column is_delivered is one to many and pulled from another model.


You can simply do like below:

'attribute'=>'is_delivered',
'format'=>'raw',
'value'=>function($row){
      $values=[
      '(1,1,0)'=>'red',
      '(1,1,1)'=>'green',
      '(1,0,1)'=>'blue',
       //other values with its color
      ];
      return Html::tag('span', $row->is_delivered, ['style'=>'background-color:'.$values[$row->is_delivered]]);
}

By above code, we hold all of our possible values, and we assign a color to each one. Then, we show the value in a span tag, with the background color specified into $values array. Also, as you can see, there is no need to use java-script , or any == or if statements.

You can improve your code like below:

['style'=>'background-color:'.isset($values[$row->is_delivered]) ? $values[$row->is_delivered] : 'white']

So, if the value is not exist in $values array, it will show it with white background. Please note that, I set background-color , you must change it to color instead.

链接地址: http://www.djcxy.com/p/31028.html

上一篇: 使用jQuery动态改变进度条的颜色

下一篇: yii2:jquery如果gridview列包含特定的值而不是改变颜色