Search code examples
jqueryformsfunctiondrupal-7parameter-passing

Drupal 6 to 7: add jquery function to form


I need to convert code from Drupal 6 to Drupal 7 but stuck at the part for jquery. In Drupal 6, the code to add jquery is as the following in which simpleColor is a function in jquery.simple-color.min.js:

drupal_add_js(drupal_get_path('module', 'module_name') . '/js/jquery.simple-color.min.js', 'module', 'header', FALSE, FALSE, FALSE);

$jquery = '
  $(document).ready(function() {
    $(".simple_color").simpleColor({
      displayColorCode: true,
      boxWidth: "6em",
      defaultColor: "#36c",
    });
  });';

drupal_add_js($jquery, 'inline');

The simple_color has been added into form:

$form['feeds']["feed_$fid"]['color'] = array(
  '#title' => t('Color'),
  '#type' => 'textfield',
  '#size' => 10,
  '#attributes' => array(
    'class' => 'simple_color',
  ),
);

I has tried to convert the above code to Drupal 7 but unsuccessful:

drupal_add_js(drupal_get_path('module', 'module_name').'/js/jquery.simple-color.min.js', array('type'=>'module', 'scope'=>'header', 'defer'=>FALSE, 'cache'=>FALSE, 'preprocess'=>FALSE));

$jquery = '
  jQuery(document).ready(function() {
    $(".simple_color").simpleColor = {
      attach: function({
        displayColorCode: true,
        boxWidth: "6em",
        defaultColor: "#36c"
    })
  };
});';

drupal_add_js($jquery, array('type'=>'inline'));

In form:

$form['feeds']["feed_$fid"]['color'] = array(
  '#title' => t('Color'),
  '#type' => 'textfield',
  '#size' => 10,
  '#attributes' => array(
    'class' => array('simple_color'),
  ),
);

I have try many ways but they didn't work for this case. Please take sometime to have a look and try to help me. Thanks ahead.


Solution

  • Applying the suggestion from 2pha, I have successfully added jquery code to drupal. The following is the fix in drupal 7:

    drupal_add_js(drupal_get_path('module', 'module-name') . '/js/jquery.simple-color.min.js','file');
    
    $jquery = '
      (function($) {
      Drupal.behaviors.myBehavior = {
        attach: function (context, settings) {
          $(document).ready(function() {
            $(".simple_color").simpleColor({
              displayColorCode: true,
              boxWidth: "6em",
              defaultColor: "#36c",
            });
          });
        }
      };
      })(jQuery);';