Context:
Select dropdown for value change(Select Solo to remove one value):
<select id="T" name="unittype" class="form-control" style="width: 100%;" required>
<option value="" hidden>Select one ...</option>
<option value="Pair">Pair</option>
<option value="Solo">Solo</option>
<option value="Pair Unit acting like a Solo Unit">Pair Unit acting like a Solo Unit</option>
<option value="Solo to Pair Unit">Solo to Pair Unit</option>
</select>
Adds values to input field:
$('input:checkbox').change((e) => {
if ($(e.currentTarget).is(':checked')) {
var curVal = $('#name').val();
if (curVal) {
$('#name').val(curVal + ', ' + e.currentTarget.value);
} else {
$('#name').val(e.currentTarget.value);
}
} else if (!($(e.currentTarget).is(':checked'))) {
var curVal = $('#name').val().split(',');
var filteredVal = curVal.filter(el => el.trim() !== e.currentTarget.value)
$('#name').val(filteredVal.join(','));
}
});
Removes Checkboxes from HTML table:
const checkboxes = document.querySelectorAll('input[type=checkbox]:checked');
if (checkboxes.length >= 2) {
checkboxes[1].checked = false;
}
Problem: When the second box that is checked unchecked, the value is still present in input field. I want the value removed. Can some help me modify the code or find a solution to my problem? I tried everything I could think of and it is not working. Note: Names in input field in photo are fictional.
Pictures:
Input field:
Table:
What I tried was Researching online and trying different things that I found and modifying it to where it fits my project. What I expected to happen was second value in input field gets removed. What really happened is that the second value did not get removed
2
Answers
You need to remove the selected option from the
select
dropdown.I have modified the code to do that. Also I changed the code to stop mixing Vanilla JS and jQuery in the same function. Now it uses only jQuery code/functions
See full demo below:
You need to define a function that will check for Solo, and if so, loop the checkboxes, uncheck those that are after the first and trigger a change event. And of course, set this as a change event for your select:
Another snippet where the behavior is triggered for all changes: