How can I enable a specific textfield using a radio button?
-
19-01-2021 - |
質問
I want to enable an 'other text' field when the 'option other' radio button is selected. I can make this work but the form must include more than one radio group. When I try to add another radio group my code causes both text fields to be enabled.
How do I make this work for just one at a time? I looked at adding :eq() to the class but I can't figure out how to make that work. Any help is appreciated.
<script>
$(document).ready(function() {
$('.textclass').attr({disabled:true,enabled:false});
$('.radclass.can').click(function(){
$('.textclass').attr({disabled:false,enabled:true});
});
$('.radclass.cant').click(function(){
$('.textclass').attr({disabled:true,enabled:false});
});
});
</script>
<form name="form1" method="post" action="next.php">
<input type="radio" name="grp_one" class="radclass cant" value="option_one" />Option One<br />
<input type="radio" name="grp_one" class="radclass cant" value="option_two" />Option Two<br />
<input type="radio" name="grp_one" class="radclass can" value="option_other" />Option Other<br />
Other Text: <input type="text" name="text_one" class="textclass"/>
<br />
<input type="radio" name="grp_two" class="radclass cant" value="option_one" />Option One<br />
<input type="radio" name="grp_two" class="radclass cant" value="option_two" />Option Two<br />
<input type="radio" name="grp_two" class="radclass can" value="option_other" />Option Other<br />
Other Text: <input type="text" name="text_two" class="textclass"/>
<br />
<input type="submit" name="submit" value="submit">
</form>
解決
You should assign a different identificator to both textfields, for example adding a classname relative at the name group:
<input type="text" name="text_one" class="textclass grp_one"/>
After that in your script you could identify which group has been clicked and than you can do your activation:
$('.radclass.can').click(function(){
var grp = $(this).attr('name');
$('.' + grp).attr({disabled:false,enabled:true});
});
Here a full example (link)
所属していません StackOverflow