How to make a choice of one of the group elements of mixed inputs?
-
06-06-2021 - |
Pregunta
How to make a choice of one of the group elements of mixed inputs?
I have following code:
<div class="item">
<input type="radio" name="group1" value="value1">Value1</input>
<input type="radio" name="group1" value="value2">Value2</input>
<input type="radio" name="group1" value="value3">Value3</input>
<textarea name="group1"></textarea>
</div>
<div class="item">
<input type="radio" name="group2" value="value1">Value1</input>
<input type="radio" name="group2" value="value2">Value2</input>
<input type="radio" name="group2" value="value3">Value3</input>
<textarea name="group2"></textarea>
</div>
I think about: when we click on textarea, radiobuttons should lost checked
atribure.
Like:
$('.item textarea').on('click', function(){
$($(this).parent + 'input[type="radio":checked]').each(function(){
$(this).checked = false;
});
});
But it not work.
I think the problem with parent
object. Thanks.
Solución
There are many problems in your variant. First, there is a problem in your selector construction: $($(this).parent + 'input[type="radio":checked]')
. Here you mix jQuery object with the string selector which is not correct. Moreover, parent element is taken with method parent()
but not a property. Then, jQuery object doesn't have checked
attribute.
Taking into consideration all the problems described we can get this workable code:
$('.item textarea').on('click', function() {
$(this).siblings(":radio").prop("checked", false);
});
DEMO: http://jsfiddle.net/TEk9c/
By the way, if you need to uncheck all radios when the user enters textarea
not only using mouse click
but using keyboard, you can use focus
event instead.
Otros consejos
If you want to base it on the name
attribute, you can use the Attribute Equals Selector:
$('.item textarea').on('click', function() {
$(':radio[name="' + this.name + '"]').prop("checked", false);
});
If the radio buttons you need will always be in the same div.item
, you can even write a stricter solution. In this example, first we find the closest parent that has the class item
, and inside it we search for the radios with the same name
attribute.
$('.item textarea').on('click', function() {
$(this).closest('.item')
.find(':radio[name="' + this.name + '"]')
.prop("checked", false);
});
One validity note: <input>
is a void element, it cannot have contents inside and a closing attribute. You have to use a <label>
element to give it a, hm, label:
<label><input type="radio" name="group1" value="value1" /> Value1</label>