My problem is:
-
When I select YES – I have border line around cell only in cell with checkbox YES – I need change it to select all rows.
-
When I select YES – I need show error message – but it’s not working. How can i change it?
// YES
$('[id^="id_0-medical_question"][id$="_0"]').click(function() {
$(this).parent().parent().css({
'border': '2px solid #da4f49'
});
$(this).parent().parent().find('.medical_error_message').html('Error - you not like this');
});
// NO
$('[id^="id_0-medical_question"][id$="_1"]').click(function() {
$(this).parent().parent().css({
'border': '1px solid #ddd',
'color': '#000000',
'font-weight': 'normal'
});
$(this).parent().parent().find('.medical_error_message').html('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<td class="medical_question"><b>1. Do you like</b></td>
<td>YES</td>
<td>NOW</td>
</tr>
<tr>
<td class="medical_question">
1. Red hair
<p class="medical_error_message"></p>
</td>
<td style="border: 2px solid rgb(218, 79, 73);"><label for="id_0-medical_question1_0"><input type="radio" name="0-medical_question1" value="1" required="" id="id_0-medical_question1_0">
YES</label>
</td>
<td><label for="id_0-medical_question1_1"><input type="radio" name="0-medical_question1" value="0" required="" id="id_0-medical_question1_1">
NO</label>
</td>
</tr>
<tr>
<td class="medical_question">
2. Blond hair
<p class="medical_error_message"></p>
</td>
<td><label for="id_0-medical_question2_0"><input type="radio" name="0-medical_question2" value="1" required="" id="id_0-medical_question2_0">
YES
</label>
</td>
<td><label for="id_0-medical_question2_1"><input type="radio" name="0-medical_question2" value="0" required="" id="id_0-medical_question2_1">
NO</label>
</td>
</tr>
3
Answers
I think your jQuery is wrong. You need to update the jQuery selectors to target all rows when selecting YES.
Here’s your updated code:
For 1, the problem is the
$(this).parent().parent().css(
which is pointing to thetd
where the radio button is, not thetr
(row). You can use$(this).parent().parent().parent().css(
but there is a better way – use$(this).closest('tr')
instead to find the firsttr
where your radio button is.For 2, it is pointing to the
td
of the radio buttons not thetd
where yourmedical_error_message
is. Use$(this).closest('tr').find('.medical_error_message')
instead since it’s unique in each row.Another thing, changing the border of your
tr
won’t reflect unless you set the style of thetable
toborder-collapse: collapse;
.Here is the modified code:
Your jQuery can be MUCH simplified using a CSS class and delegation
Note the table css to make the row actually get a border