Gilang Tartila Gilang Tartila - 6 months ago 111
PHP Question

How to disable button when text input is empty in yii2?

I want to disable button when text input is empty in yii2?
can you help me?
this is my code

<div class="pemesanan-search thumbnail padding-baru col-sm-6 input">

<?php $form = ActiveForm::begin([
'action' => ['menubayar'],
'method' => 'get',
]); ?>

<?= $form->field($model, 'NO_REKENING') ?>

<?= $form->field($model, 'NO_KARTU') ?>

<?= $form->field($model, 'NAMA') ?>

<div class="form-group">
<center><?= Html::submitButton('Cek Kartu Kredit', ['class' => 'btn btn-default']) ?></center>

<?php ActiveForm::end(); ?>



First disable the submit button by default, by using disabled attribute in button's option.

After that you have to register a JS code using Yii2 RegisterJS.

Then trigger event using jQuery to remove disabled attribute after the input value is changed.

$( "# [id of the input that needs value]" ).change(function() {

By using above code, if you change the value of the input whith this id, it means that its not empty anymore and the disabled attribute will be removed.

Or also you can check if $("# [id of the input that needs value]").val(); is not empty remove the disabled attribute again with this code:


P.S: You may also define rules in its model and make that attribute as Required in the model rule, and let Yii handles the validation. You can learn more about that by reading This document.