Ezequiel Flores
Ezequiel Flores

Reputation: 37

Drupal 7 Form api Custom javascript with Jquery

I am developing with Drupal 7 a custom form with form API and a tableselect with checkboxes. i have some constrains to do for the selection of the checkboxes that i want to code with jquery. i made a function for the onclick checkbox, outside drupal it works like you can see HERE, but when i try to integrate with drupal, the jquery selector doesnt work at all.

so here is my code in in drupal:

$form ['#attached'] ['js'] = array (drupal_get_path ( 'module', 
    'form_cuentacorriente' ) . '/checkboxes.js' );
$form ['tabla'] = array (
    '#type' => 'tableselect',
    '#header' => $tabla ['header'],
    '#options' => $tabla ['body'],
    '#attributes' => array ('id' => 'conceptos')
);

and here is my js function:

(function($){
$('input[type=checkbox]').click(function(){
      var tabla = $("#conceptos")[0];
      var long = tabla.rows.length;
      var pos = $(this).closest("tr").index();

      if (!this.checked){
      for (i = pos+1; i < long +1; i++) {     
      $(tabla.rows[i]).find( 'input' ).prop('disabled', !this.checked).prop('checked', false);
      }
      }else{
      $(this).closest("tr").next().find("input")
          .prop('disabled', !this.checked);
      }  
});  
})(jQuery);

if i use the * selector, it works everywhere i click, but 'input[type=checkbox]' doesnt work. JQuery 1.10 version on Drupal 7

any ideas what i am missing?

thanks in advance!

Upvotes: 1

Views: 523

Answers (1)

Ezequiel Flores
Ezequiel Flores

Reputation: 37

SOLVED: i just needed to wrap my js function like this because of Drupal behaviors:

Drupal.behaviors.form_cuentacorriente = {
    attach: function (context, settings) {

  $('input[type=checkbox]').click(function(){
    var tabla = $("#conceptos")[0];
    var long = tabla.rows.length;
    var pos = $(this).closest("tr").index();

    if (!this.checked){
    for (i = pos+1; i < long +1; i++) {     
    $(tabla.rows[i]).find( 'input' ).prop('disabled', 
    !this.checked).prop('checked', false);
    }
    }else{
    $(this).closest("tr").next().find("input")
      .prop('disabled', !this.checked);
    }  
  });    

}

Reference: https://www.lullabot.com/articles/understanding-javascript-behaviors-in-drupal

Upvotes: 0

Related Questions