I have the following HTML:
<form id="test">
<input type="radio" value="A" name="C1"/>
<a href="javascript:selectCheckbox('C1', 'A');"> OPTION-A </a>
<input type="radio" value="B" name="C1"/>
<a href="javascript:selectCheckbox('C1', 'B');"> OPTION-B </a>
<input type="radio" value="C" name="C1"/>
<a href="javascript:selectCheckbox('C1', 'C');"> OPTION-C </a>
// several other: C2, C3, ..
</form>
And I'm trying to implement selectCheckbox( chkbox, value)
, which should:
name = chkbox
and set attr('checked') = false
name = chkbox AND val() = value
and set attr('checked') = true
I can't figure out, what the right selector is, I tried the following without any luck:
var name = "#" + chkbox + " :checked";
$(name).each(.. // doesn't work
$('#'+chkbox).each( .. // if finds only the first occurence
// of i.e. C1, although I would expect 3
$("input[@name='"+chkbox+"']").each( function() { ..
// leaves me with the following error:
// Warning: Expected attribute name or namespace but found '@name'
Please let me know what I'm doing wrong. Many, many thanks!
To get an array of selected checkboxes values we need to use jQuery each() method and :checked selector on a group of checkboxes. The each() method will loop over the checkboxes group in which we can filter out selected checkboxes using :checked selector.
To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);
Try this:
$('input:radio[name="' + chkboxName + '"][value="' + value + '"]')
.attr('checked', 'checked');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With