Rajiv Rajiv - 6 months ago 27
Javascript Question

enable disable textbox using JQuery

I am very new to JQuery, please consider me as a novoice. I have an PHP form where in I have a Radio button. Based on the which radio is selected I would like to disable the textbox. Below is the scenario:

Radio Button : Cash and Cheque
Textbox: Cheque No and Cheque Date

By default, Textbox Cheque No and Cheque Date are set to be disabled and Radio Cash is Checked.


  1. When the user clicks on Cheque Radio, textbox cheque no and cheque date must be enabled and if possible it should be made as required.

  2. When the user clicks back on Cash, textbox Cheque No and Cheque Date must be disabled and required property must be removed.



I have added JQuery 1.12.3 min to my header.php

Header.php

!-- JQuery 1.12.3 JS -->
<script src="../js/jquery-1.12.3.min.js"></script>


MainPage.php

<tr>
<td class="col-md-4"><label class="control-label" for="payMode">Mode</label></td>
<td class="col-md-8">&nbsp;
<label class='radio-inline'><input type='radio' name='rbPayMode' id='bd' value='0' checked>Cash</label>
<label class='radio-inline'><input type='radio' name='rbPayMode' id='bd' value='1'>Cheque</label>
</td>
</tr>
<tr>
<td class="col-md-4"><label class="control-label" for="ChequeNo">Cheque No</label></td>
<td class="col-md-8"><input type="number" name="txtChequeNo" pattern="^[0-9]" min="0" step="1" class="form-control" placeholder="Enter Cheque No" disabled></td>
</tr>
<tr>
<td class="col-md-4"><label class="control-label" for="ChequeDate">Cheque Date</label></td>
<td class="col-md-8"><input type="date" name="txtChqueDate" class="form-control" placeholder="Enter Cheque Date" disabled></td>
</tr>


Please Help

Answer

You can do it like following.

$(':radio[name=rbPayMode]').change(function () {
    var prop = this.value == 0;
    $('input[name=txtChequeNo], input[name=txtChqueDate]').prop({ disabled: prop, required: !prop });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td class="col-md-4"><label class="control-label" for="payMode">Mode</label></td>
        <td class="col-md-8">
            &nbsp;
            <label class='radio-inline'><input type='radio' name='rbPayMode' id='bd' value='0' checked>Cash</label>
            <label class='radio-inline'><input type='radio' name='rbPayMode' id='bd' value='1'>Cheque</label>
        </td>
    </tr>
    <tr>
        <td class="col-md-4"><label class="control-label" for="ChequeNo">Cheque No</label></td>
        <td class="col-md-8"><input type="number" name="txtChequeNo" pattern="^[0-9]" min="0" step="1" class="form-control" placeholder="Enter Cheque No" disabled></td>
    </tr>
    <tr>
        <td class="col-md-4"><label class="control-label" for="ChequeDate">Cheque Date</label></td>
        <td class="col-md-8"><input type="date" name="txtChqueDate" class="form-control" placeholder="Enter Cheque Date" disabled></td>
    </tr>
</table>