Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: select checkbox based on name and value

Tags:

jquery

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:

  1. search for all radio's with name = chkbox and set attr('checked') = false
  2. search for the radio having 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!

like image 591
MrG Avatar asked Sep 19 '09 17:09

MrG


People also ask

How can we get the value of selected checkboxes in a group using jQuery?

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.

How check checkbox is checked or not in name jQuery?

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);


1 Answers

Try this:

$('input:radio[name="' + chkboxName + '"][value="' + value + '"]')
    .attr('checked', 'checked');
like image 97
Rohan Avatar answered Sep 30 '22 21:09

Rohan