Relate a checkbox with another input

I’m trying to do something. I have the following code snippet:

echo "<form class='additionals'>";               
foreach($connection->query($sql2) as $additional)
{
    echo "<input class='additional-checkbox' type='checkbox' name='additional_id'
            value='{$additional['additional_id']}'/>
        {$additional['additional_name']} - &#36;{$additional['additional_price']}
        <input type='number' name='additional_quantity' value='1' min='1' max='5'/>
        <br/>";
}
echo "</form>";

What I need is when any checkbox with name additional_id is not checked, the input in front of it with name additional_quantity related to their quantity is disabled and vice-versa. But I do not know how to do this, even more because I need to use foreach. Can I do this with jQuery?

Answer

This will do what you need:

  • Note that I gave the checkboxes the class enable
  • I have also added the disabled property to the actual html inputs, you’ll need to add this in your php code
  • I also gave each input a unique name If you’re allowing multiple fields and will be submitting the form, they will all need unique names

$('.enable').change(function(){
     var set =  $(this).is(':checked') ? false : true;      // ternary operator to test if the changed checkbox is now checked
     $(this).nextAll('input').first().attr('disabled',set); // find the next input and set it's disabled property according to the previous check  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='additionals'>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id1' value='somevalue' />somevalue
  <input type='number' name='additional_quantity1' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id2' value='somevalue' />somevalue
  <input type='number' name='additional_quantity2' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id3' value='somevalue' />somevalue
  <input type='number' name='additional_quantity3' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id4' value='somevalue' />somevalue
  <input type='number' name='additional_quantity4' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id5' value='somevalue' />somevalue
  <input type='number' name='additional_quantity5' value='1' min='1' max='5' disabled/>
  <br/>
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *