priyo priyo - 4 months ago 11
jQuery Question

how to disable one of the input field if it does not qualify

I was a beginner in script programming. My problem is how to disable one of the input field if it does not qualify in the following cases. if the user select a cash-In, the input field with the attributes name of credit must be disabled, so that the user can not fill it. vice versa if the user select a cash-Out, then input field with debit attributes name should be disabled.
I tried to create those script, but it does not run properly.

<script type="text/javascript" src="jquery.min.js"></script>
<script>
$('#acc').click(function(){
var account = $("select#acc").val();
if (account == "db"){
$('#credit').prop('disabled', true);
}
else if (account == "cr"){
$('#debit').prop('disabled', true);
}
});
</script>
<table>
<tr><td>Account</td><td>Debet</td><td>Credit</td></tr>
<tr>
<td>
<select id="acc" name="acc" required="required">
<option value=""></option>
<option value="db">Cash-In</option>
<option value="cr">Cash-Out</option>
</select>
</td>
<td><input type="text" id="debit" name="debit" /></td>
<td><input type="text" id="credit" name="credit" /></td>
</tr>
</table>

Answer

use .change() event instead of .click() event.

$('#acc').change(function(){
    var account = $("select#acc").val();
    if (account == "db"){
        $('#credit').prop('disabled', true);
        $('#debit').prop('disabled', false);
    }
    else if (account == "cr"){
        $('#debit').prop('disabled', true);
        $('#credit').prop('disabled', false);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr><td>Account</td><td>Debet</td><td>Credit</td></tr>
<tr>
    <td>
        <select id="acc" name="acc" required="required"> 
            <option value="">Select</option>
            <option value="db">Cash-In</option>
            <option value="cr">Cash-Out</option>
        </select>
    </td>
    <td><input type="text" id="debit" name="debit" /></td>
    <td><input type="text" id="credit" name="credit" /></td>
</tr>
</table>

Comments