1

I have two blocks of code which basically check for 1) a click event on a radio button e.g.

$("input[id='frmSkill']").click(function(){ 
      //do something
});

And 2) a block of code to check if a radio button is :checked, if so, then perform some actions e.g.

if($("input[id='frmSkill']:checked").val()){
      //do something
});

What I'd like to do is combine the two in order to reduce the code as the actions performed under each are the same.

4 Answers4

3
$("input[id='frmSkill']").click(function(){ 
      if($(this).is(":checked")) {
          // do something, e.g.
          alert($(this).val());
      } else {
          // do something else
      }
});

I think you're looking for the is traversal method.

karim79
  • 339,989
  • 67
  • 413
  • 406
0

I think the "change" event is more adapted to a checkbox:

    $("input[id='frmSkill']").bind('change',function(){ 
      if($(this).is(':checked')){
         // do something
      }
    });
pixeline
  • 17,669
  • 12
  • 84
  • 109
0

A separate function that can be used in both cases:

function OnClickOrCheck(){
// code for both cases here
}

$("input[id='frmSkill']").click(OnClickOrCheck);

if($("input[id='frmSkill']:checked").val()){
OnClickOrCheck();
}
CiscoIPPhone
  • 9,457
  • 3
  • 38
  • 42
0

Why are you all complicating everything?

$("input[id='frmSkill']").change(function(){
    // Your Code Here
});
cusspvz
  • 5,143
  • 7
  • 30
  • 45
  • Change won't work though. I'm using :checked to show the correct content after php validation, if validation fails, I need to know which content to show. –  Apr 12 '10 at 10:58
  • Are you using the callback function from ajax? what you want need to be handled by ajax callback function, not by the change or checked function. – cusspvz Apr 12 '10 at 17:22