Friday, March 4, 2011

Using jQuery, how to locate an element when the Name and Value are known

Thanks for reading this

I thought I could use find(), but couldn't make it work. I know I can add IDs or classnames, but would like to know how with the current markup.

Thanks

Here is the HTML

<input name="keywordCheckbox" type="checkbox" value="S" />
<input name="keywordCheckbox" type="checkbox" value="C" />
<input name="keywordCheckbox" type="checkbox" value="A" />

and the js

<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

 $(function(){
  $('[name="keywordCheckbox"]').bind("click",
   function() {
    if($(this).attr("checked") == true) {
     switch(this.value) {
      case "A":
       var $_this = $(this) ;
       $('[name="keywordCheckbox"]').each(function() {
        if($(this).val() != $($_this).val()) { $(this).attr("checked",false); }
       });
       break ;
      default:
 DOESN'T WORK --> $('[name="keywordCheckbox"]').find('[value="A"]').attr("checked", false);}
      } // END Switch
    } // END If
  }); // End BIND
 }); // End eventlistener
 </script>
From stackoverflow
  • Or you could do:

    $("input[name='keywordCheckbox']").filter("input[value='A']")
    

    Then there is no need for an each function.

  • You should be able to chain the attribute selectors:

     $('input[name="keywordCheckbox"][value="A"]').attr("checked",false);
    

    Will set checked to false for the input with name keywordCheckbox and value of A.

     $('input[name="keywordCheckbox"][value!="A"]').attr("checked",false);
    

    will set checked to false for the inputs with name keywordCheckbox whose values are not A.

    EDIT

    I just tested the following in Firefox/Macintosh with the latest jQuery. Works fine. What version of jQuery are you using?

    $(document).ready( function() {
        $('input[name=keywordCheckbox]').bind( 'click', function() {
           if (this.checked) {
              if (this.value == 'A') {          
              $('input[name="keywordCheckbox"][value!="A"]')
                 .attr("checked",false);
              }
              else {
              $('input[name="keywordCheckbox"][value="A"]')
                 .attr("checked",false);
              }
           }
        });
    });
    
    CarolinaJay65 : my apologies, I tested your code and it worked fine. originally, you had a ^ instead of a ! for the negative test, but I thought I had tested it both ways...maybe I included a space between the [name] and [value]..anyway I like your solution...gave an upvote and selected this answer
    tvanfosson : Yeah. I noticed that typo and fixed it later. Thanks.

0 comments:

Post a Comment