Home > Net >  How to change check/uncheck listbox when click checkbox in Javascript
How to change check/uncheck listbox when click checkbox in Javascript

Time:03-26

I'm usig div and id of css to check and uncheck in checkbox, but my source cannot as expected

step 1: as default checkbox is uncheck and listbox is disable

step 2: when i check checkbox, listbox is enable

step 3: back step 1, if i uncheck checkbox, listbox is disable

my souce:

$('#parnerCheck2').click(function() {
  $('#partnerName').prop("checked", false).prop("disabled", true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
  <th scope="row">Partner</th>
  <td colspan="1" style="margin-top: 4px;">
    <input id="parnerCheck2" name="parnerCheck" type="checkbox" value="0" /><span>PARTNER</span>
  </td>
  <td>
    <select id="partnerName" name="partnerName">
      <option value="" selected>Choose One</option>
      <option>01 - Elite</option>
    </select>
  </td>
</tr>

How to fix the problem as my description? thank a lot

CodePudding user response:

You where almost there. You can set disabled property on the list box with the checked value of the checkbox, prefixed with the not operator ! to reverse the value, to get the result you want.

$('#parnerCheck2').click(function() {
  $('#partnerName').prop("disabled", !$(this).prop("checked"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
  <th scope="row">Partner</th>
  <td colspan="1" style="margin-top: 4px;">
    <input id="parnerCheck2" name="parnerCheck" type="checkbox" value="0" /><span>PARTNER</span>
  </td>
  <td>
    <select id="partnerName" name="partnerName" disabled>
      <option value="" selected>Choose One</option>
      <option>01 - Elite</option>
    </select>
  </td>
</tr>

CodePudding user response:

This would also work.

<body>
    <script>
        $(document).ready(function() {
        //set initial state.
        $('#partnerName').prop('disabled', true);

        $('#partnerCheck').click(function() {
            if ($('#partnerCheck').is(':checked')) {
                $('#partnerName').prop('disabled', false);
            }
        });
        });
    </script>
 
 
    <tr>
        <th scope="row">Partner</th>
        <td colspan="1" style="margin-top: 4px;">
            <input id="partnerCheck" name="partnerCheck" type="checkbox" value="0" /><span>PARTNER</span>
        </td>
        <td>
            <select id="partnerName" name="partnerName">
                <option value="" selected >Choose One</option>
                <option>01 - Elite</option>
            </select>
        </td>
    </tr>
</body>
  • Related