MrG MrG - 2 years ago 64
Javascript Question

jQuery: select checkbox based on name and value

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, ..

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!

Answer Source

I'd use relative DOM position to do the navigation. Note also you can't have different elements with the same id, but in this case it isn't necessary since you can use the attribute selector on the name to find the correct inputs. Note that you already know which of the various inputs need to be checked based on the position of the link that is clicked. I prefer to have the code separate from the markup so I've given the links a class to make them easy to select and moved the click handler application into the code.

Update: Note that I removed the code to uncheck the other radios. With radios, setting one to checked should automatically uncheck any of the others.

$(function() {
     $('a.checkbox-selector').click( function() {
         // get the checkbox immediately preceding the link -- this should
         // be checked.  Checking it should automatically uncheck any other
         // that may be checked.
         return false;  // don't process the link

<form id="test">
  <input  type="radio" value="A" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-A </a>

  <input  type="radio" value="B" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-B </a>

  <input  type="radio" value="C" name="C1"/>
  <a href="#" class="checkbox-selector"> OPTION-C </a>

  <!-- several other: C2, C3, ... -->
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download