Reputation: 3607
I'm creating a table
that's trying to combine two forms of conditional logic:
1). enabling/disabling
a field depending on the < select >
value from a dropdown
from another td
in the row.
2). Using the blur
method to change the CSS of that same field if it's not filled out correctly AND enabled
. If it's disabled
I want jQuery to disregard the validity of the input
since it won't be used later on in the program.
I have two functions that work fine separately but when I try and combine them they don't work correctly.
Here's sample HTML:
<tr class="formulaRow">
<td>
<select class="tableDropDown">
<option value="other">The Manufacturer</option>
<option value="me">Me</option>
</select>
</td>
<td>
<input class="packSize" type="number" disabled>
</td>
</tr>
Here's the jquery function to enable/disable the ".packSize" input based on the dropdown:
$(".tableDropDown").on('change', function(){
var packSize = $(this).parents('.formulaRow').find('.packSize');
if ($(this).val() === "me") {
$(packSize).prop('disabled', false);
} else {
$(packSize).prop('disabled', true);
}
});
Here's the jquery for changing the background color if the input is not a number in ".packSize"
$(".packSize").blur(function() {
var tableDropDown = $(this).parents(".formulaRow").find(".tableDropDown");
if ($(this).val() ==="" && $(tableDropDown).val() === "me") {
$(this).parents("td").addClass("redClass");
}
else {
$(this).parents("td").removeClass("redClass");
}
});
I've also tried to use && $(this).prop("disabled", false)
in the if statement but it didn't work either.
The issue is that, if you disable the input
field and it has redClass
attached to it, it doesn't detach
and still has a red background
.
I want redClass
to automatically toggle off if .packSize
is disabled
.
Upvotes: 0
Views: 61
Reputation: 2269
Hopefully this will work for you.
I just referenced the parent td
element again and removed the class. Even if it isn't there, you can still "remove" it.
$(".tableDropDown").on('change', function(){
var packSize = $(this).parents('.formulaRow').find('.packSize');
if ($(this).val() === "me") {
$(packSize).prop('disabled', false);
} else {
$(packSize).prop('disabled', true);
$(packSize).parents('td').removeClass("redClass");
}
});
$(".packSize").blur(function() {
var tableDropDown = $(this).parents(".formulaRow").find(".tableDropDown");
if ($(this).val() ==="" && $(tableDropDown).val() === "me") {
$(this).parents("td").addClass("redClass");
}
else {
$(this).parents("td").removeClass("redClass");
}
Upvotes: 1