Yevgeniy Bagackiy Yevgeniy Bagackiy - 2 months ago 7
Javascript Question

Enable input field after checkbox is checked in list of checkboxes

I have a list of data getting from database, and i want to enable input field on checked checkbox. However its working only with the first line. Here is HTML code:

<?php
require_once('inc/config.php');
include 'verification/verify_form_details.php';
?>
<html>
<head>
<title>getElementById example</title>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
</head>
<body>
<?php
$result2 = getProcessID();
?>
<label>Process: <small style="color:red;">*</small>
<?php
while ($row = mysql_fetch_array($result2))
{
$row[0] = cleanOutputData($row[0]);
?>
<div>
<label>
<input type="checkbox" class="checkbox" name="process[]" id=<?php echo $row[0] ?> value=<?php echo $row[0]?> /><?php echo $row[0] ?>
</label>

<label>
<input type="text" class="field" disabled name="number[]" id=<?php echo $row[0] ?> />
</label>

</div>
<?php
}
mysql_free_result($result2);
?>
</label>
</body>
</html>


And javascript function:

<script>
$(document).ready(function () {
$('.checkbox').change(function() {
$('.field').attr('disabled',!this.checked)
});
});
</script>


Any ideas how i can do it? Thank you

Answer

$('.checkbox').change(function() {
  $(this).parent().next().find('.field').prop('disabled', !$(this).is(':checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox" class="checkbox" name="process[]" id=v alue=/>
</label>

<label>
  <input type="text" class="field" disabled name="number[]" id=/>
</label>


<label>
  <input type="checkbox" class="checkbox" name="process[]" id=v alue=/>
</label>

<label>
  <input type="text" class="field" disabled name="number[]" id=/>
</label>


<label>
  <input type="checkbox" class="checkbox" name="process[]" id=v alue=/>
</label>

<label>
  <input type="text" class="field" disabled name="number[]" id=/>
</label>

  1. Use class instead of ID
  2. Use this context to refer to changed element
Comments