Skip to content Skip to sidebar Skip to footer

Programmatically Click On Label/Radio Or Fire Event

I'm writing a userscript that injects a custom javascript into the head of a page. Easy peasy // ==UserScript== // @name *** (BLOCKED DUE TO NDA) // @namespace *** (BLOCKED D

Solution 1:

Check out jQuery#trigger. It will let you raise events willy nilly. :)

In this case it would be something like:

$('#form-'+i+'-status_D').trigger('click');

Also, I would suggest some refactoring:

// If Name Length is <= 3 or >= 15 Apply Color (Red)
if (nlen <= 3 || nlen >= 15) {
  $(this).css('background-color','#FF7575').
    addClass('AddDeleted').
    removeClass('AddApproved').
    removeClass('AddInactive');
}

jQuery functions can generally be chained, so you don't need to (and shouldn't) repeatedly do $(this). At worst, you should do something like var self = $(this) and then use self instead of rerunning jQuery's wrapper on this over and over again.


Based on your comments, the effect you get from clicking the 'Click Me' span in the following example is what you're after?

<html>
  <head>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        $('#click-me').click(function() {
          $('label[for=test]').trigger('click');
        });
      });
    </script>
  </head>
  <body>
    <span id="click-me">Click Me</span>
    <input type="radio" id="test">
    <label for="test">Deleted</label>
  </body>
</html>

Solution 2:

Trigger won't work as I explained on the other question you asked. The other answer seems to be correct as you focused on Trigger only.

Seems like you don't have any JS code associated with the radio buttons. In this case I would do:

$(_self).children('#form-'+i+'-status_D').prop("checked", true);

That's all you need.


Post a Comment for "Programmatically Click On Label/Radio Or Fire Event"