简体   繁体   中英

Yii2 hide form field onchange radio

I have a radioList with 2 values, 1 and 2. I would like to hide textInput if the radio is set to 2. I have tried:

$script = <<< JS

$(document).ready(function () {
    if(document.getElementById('radio').val() == '2' ) {
        document.getElementById('textInput').style.display = 'none';
        document.getElementById('textInput').hide();
    } else {
        document.getElementById('textInput').show();
    }
});

JS;
$this->registerJs($script);

echo $form->field($model, 'radio')->radioList(['1' => '1', '2' => '2'], ['id' => 'radio']);
echo $form->field($model, 'textInput')->textInput(['id' => 'textInput']);

Any ideas?

Multiple problems with your code

  • You are not loading/registring the script anywhere using $this->registerJs($script,\\yii\\web\\View::POS_READY) .
  • There isn't any method with the name .val() but .value when using javascript document.getElementById() .
  • There isn't any method .show() and .hide() in javascript
  • Then even if you would have done the above steps it would still not work because you are not binding any event to the radio inputs your script is just an inline script which would be called when the page is loaded.
  • The id radio you are providing in the radioList will be id of the container in which all the radio list inputs are residing.
  • And you need to hide the complete container of the input, not just the input so that the label is also hidden and shown along with the input.

Since you have used the javascript tag I am using addEventListner to bind the event see the code below and add it to the top of your view.

$script = <<< JS
document.querySelectorAll("#radio input[type='radio']").forEach(function(element){
    element.addEventListener('click',function(){
        if(this.value == '2' ) {
            document.querySelector('#textInput').parentElement.style.display = 'none';
        } else {
            document.querySelector('#textInput').parentElement.style.display = 'block';
        }
    });
});
JS;
$this->registerJs($script, \yii\web\View::POS_READY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM