jquery conditional statement for 2 form elements with same class
This is probably a simple question, but I can't figure it out so I'm asking the community.
I have a select list and a text field in a form. They both have the same class.
I want to find a clean conditional statement that will allow me to disable a set of radio buttons in another part of the form if the text field is not empty AND something other than the default value is selected in the select list.
So far, I can only开发者_如何转开发 get it working for the text field:
$('.affector').change(function(){
if ($(this).val() !== '') {
$(this).parents('tr').find('input:radio').attr('disabled', false);
} else {
$(this).parents('tr').find('input:radio').attr('disabled', true);
}
});
..and it works upon the initial change of the select list, but for some reason, I can't figure out how to get the 'else' part of the conditional to fire if I select the default value again (and the text field is empty).
Oh yes, the select list is dynamically populated, so I'll probably have to use BIND... and there are multiple select fields on the page so thats why I went with a class.
Any ideas?
UPDATE: Here is the HTML...
<tr bgcolor=#ffffff>
<td valign=center>
Batter # 1
<div id="txtResult1">
<select name="player1" class="affector">
<option></option> //dynamically populated
</select>
</div>
<input type="text" id="PlayerLocal1" class="affector" name=p1name size=20>
</td>
<td>
<table border=1>
<tr>
<td>
<table border=0 cellspacing=0 cellpadding=0>
<tr>
<td><input type=radio name=p1o1 value="1B">1B</td>
<td><input type=radio name=p1o1 value="FO">FO</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
Right now you are only ever checking one value instead of both, if I understand correctly. That is, if the change
event of the select element fires, only the select element's value is tested, and if the change
event of the text field fires, only the value of the text field is checked. However, you want both to be checked (AND), so I suggest something like this:
$('.affector').change(updateRadioEnabled);
function updateRadioEnabled() {
var valueGiven = true;
$('.affector').each( function() {
if ($(this).val() == "") {
valueGiven = false;
}
});
var radio = $('.affector:first').parents('tr').find('input:radio');
if (!valueGiven) {
radio.attr('disabled', true);
} else {
radio.removeAttr('disabled');
}
}
EDIT: Notes: Community wiki is usually for questions that invite for an exchange of opinions in contrast to crisp technical answers. Your question is clearly technical.
.affector:first
will find the first element with the affector
class and then stop searching. I often do this for efficiency (however see Brandon's comment below). Here, I simply select this element to have a starting point from which to find the radio buttons. There is probably a more elegant solution.
EDIT: By the way, why is this community wiki?
精彩评论