Yii2 concatenate a variable to String in whenClient

1.1k views Asked by At

I am using a dynamic form with validation rules and I want to make the browser validate also the form before it submit so I used whenClient. There is a checkbox that when clicked, will not process validation...

['dv_number', 'required', 'when' => function ($model) {
        return $model->is_cancelled == 1;
        }, 'whenClient' => "function (attribute, value) {  
            console.log(attribute.name);
            var firstletter=(attribute.name.charAt(0));
            var index='';
            if(firstletter==='['){ //when dynamic form is not activated and name of inputs is like [0]dv_number
                index=attribute.name.charAt(1);//I get the array index
            }else{
                index=attribute.name.charAt(9);//dynamic form activated the name of inputs changed like this TblDvBub[0][dv_number].
            }

            if($('[name=\'TblDvBub[0][is_cancelled][]\']').is(\":checked\"))
            {
                return false;//validation will not take place
            }
            else
            {
                return true;//validation from browser takes place
            }

        }"
    ],

So I get the index number using the index variable. My problem is to replace the 0 in this line if($('[name=\'TblDvBub[0][is_cancelled][]\']').is(\":checked\")) to index and make it like this if($('[name=\'TblDvBub[index][is_cancelled][]\']').is(\":checked\"))

NOTE that the whole code starting from when client is enclosed by " "...

I have tried this and a lot others but to no avail.

if($('[name=\'TblDvBub[' + index +'][is_cancelled][]\']').is(\":checked\"))

enter image description here

1

There are 1 answers

1
robsch On BEST ANSWER

This is just a JS/jQuery/PHP issue. You have to escape the brackets in the name filter of the selector:

if($('[name=TblDvBub\\[' + index + '\\]\\[is_cancelled\\]\\[\\]]').is(\":checked\"))

Not quite sure, but when this is within a "" string in PHP you have to even double the escaping characters:

if($('[name=TblDvBub\\\\[' + index + '\\\\]\\\\[is_cancelled\\\\]\\\\[\\\\]]').is(\":checked\"))

I think this is the problem here. Does it help? Is the first or second way correct?

See jQuery doc (noted in the starting paragraph).