Nicole Foster Nicole Foster - 2 months ago 8
jQuery Question

jQuery - Checkbox checked enables field next to it in table

I currently have a table with a checkbox and product name on one side, then a quantity input field on the other side. By default, the quantity field is disabled, but I would like to enable it only if its corresponding product is checked.

I'm still new to jQuery and a bit stuck on this, so this is a best I could come up with:



$(document).ready(function(){

//enable quantity field if product is selected
$("input[name='quantity']").prop('disabled', 'true');
$(".product").on('click', function(){
$next = $(this).next();
$next.prop('disable', 'false');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="products">
<thead>
<tr>
<th>Product Name</th>
<th width="150">Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
<tr>
<td><input type='checkbox' id='product' class='product' name='product'><label>Product</label></td>
<td><input type='text' placeholder='0' name='quantity' id='quantity'></td>
</tr>
</tbody>
</table>




Answer

You have duplicate IDs for input element. IDs must be unique. you can rather use classname and then use class selector to target element by classname.

And your solution is not working because

1) you have wrong selector to target next input element. you need to traverse to closest tr and then find element with name quantity in it.

2) You are setting wrong property. you need to use disabled instead of disable :

$(".product").change(function(){
   $next = $(this).closest('tr').find('[name=quantity]');
   $next.prop('disabled', this.checked);
});

Working Demo