Search code examples
jqueryhtmlonchangedisabled-input

How to disable an input on change of other inputs (jQuery)


I'd like to add an attribute disabled to input #stock if whichever value of #option_name-x is not empty. My code works only if I enter something into #option_value_1, but it doesn't work if I leave #option_value_1 empty and enter something into #option_value_2 or the following. In other words, the code works with the first input only.

<tr>
    <td><input name="option_name[]" id="option_name_1" type="text"></td>
</tr>
<tr>
    <td><input name="option_name[]" id="option_name_2" type="text"></td>
</tr>
<tr>
    <td><input name="option_name[]" id="option_name_3" type="text"></td>
</tr>
<tr>
    <td><input name="option_name[]" id="option_name_4" type="text"></td>
</tr>
<tr>
    <td><input name="option_name[]" id="option_name_5" type="text"></td>
</tr>
<tr>
    <td>
        Stock (*disabled if any option_name field is NOT EMPTY*)<br>
        <input name="stock" id="stock" type="text">
    </td>
</tr>


// on input change
    $("input").change(function() {
// i want to react on whichever input with id starting with "option_name"
        if($("[id^='option_name']").val() !== "") {
            $("#stock").attr('disabled', 'disabled');
        } else {
            $("#stock").removeAttr('disabled', 'disabled'); 
        }
})

Solution

  • I hope this will work perfectly for you, always remember on is better in this scenario, and you might need to execute it on paste as well

    // on input change
    $("input").on("change paste keyup", function() {
      var optionsInputHavevalue = $("[id^='option_name']").filter(function() {
        return $(this).val().trim().length > 0 ;
      }).length > 0;
      $("#stock").prop('disabled', optionsInputHavevalue);
    }).change();
    

    working bin can be found here. https://jsbin.com/zojukij/edit?html,js,output