0

I am trying to get JavaScript to measure a text field and auto submit at a character limit for an Ajax callback to be validated against a Luhn Algorithm and errors out on failure to validate.

I found this code in Firing ajax_callback on textfield after a minimum number of character.

// Trigger ajax event on myitem only after 5th character typed.
$('.myitem-class').on('keyup', function() {
  if ($(this).val().length == 5) {
    $(this).trigger('change');
  }
});

The JavaScript can allegedly be put inline in a wrapper like this to be used in an Ajax callback in a form. See drupal_add_js within AJAX callback.

function my_module_form($form, &$form_state) {
  drupal_add_js('Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
    // …
    }',
    'inline'
  );

  return $form;
}

I got to run replacing function(ajax, response, status) with function($, Drupal).

When I put in the code, it throws a PHP error at ).on(. I wasn't able to get the inline wrapper recommended in Converting 6.x modules to 7.x / JavaScript should be compatible with libraries other than jQuery to work because it fails seeing the $ as a variable.

(function ($) {
  // […]
}(jQuery));

Right now, I am stopped by syntax errors.

Does anyone know how to get this JavaScript code work?

1

Quick written code:

      <?php

      /**
        * Form.
        */
      function sample_luhn_form($form, &$form_state) {
        // I don't recommend inline js, prefer usual module js file, attach via $form['#attached'] or in module info file
        // Also I am use jQuery instead of $, but your shown (function ($) { }jQuery)); is preferred, I don't know why it's show errors, try inspect on dev.tools
        drupal_add_js('jQuery(document).ready(function () { jQuery(".luhn-nums").keydown(function() { if (jQuery(this).val().length >= 5) { jQuery(".luhn-check").mousedown(); } }); });', 'inline');


        // text field that should be checked for Luhn
        $form['luhn_nums'] = array(
          '#type' => 'textfield',
          '#title' => t('Luhn numbers'),
          '#prefix' => '<div class="luhn-nums-wrapper">',
          '#suffix' => '</div>',
          '#attributes' => array(
            'class' => array('luhn-nums'),
          ),
        );
        // hidden ajax button
        $form['luhn_check'] = array(
          '#type' => 'submit',
          '#ajax' => array(
            'callback' => 'sample_luhn_form_ajax_submit',
            'wrapper' => 'luhn-nums-wrapper',
          ),
          '#attributes' => array(
            'class' => array('luhn-check', 'element-invisible', 'hidden'), // set class, that hide this ajax submit button or hide via CSS styles
          ),
        );

        // here goes another form elements
        // ...
        $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
        );
      }

      /**
       * Ajax callback function.
       */
      function sample_luhn_form_ajax_submit($form, &$form_state) {
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
        // here you can alter luhn_nums textfield value
        return $form['luhn_nums'];
      }

      /**
       * Validate form.
       */
      function sample_luhn_form_validate($form, &$form_state) {
        // Don't allow pass to submit untill luhn will passed
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
      }

      /**
       * Form submit.
       */
      function sample_luhn_form_submit($form, &$form_state) {
        // save data
      }

      /**
       * Private function that check luhn algorithms.
       */
      function _sample_luhn_check($nums) {
        $result = FALSE;

        // check numns by luhn algorithms
        // lot of code that alter $result

        return $result;
      }
3
  • Thanks - that is really close to what I had except for the " drupal_add_js('jQuery(document).ready(function () . . ." way to call JQuery. I had seen that in some cases the function($) wrapper does not work, and this was going to be my next try. I will try to cobble up this for the code and report back Apr 5 at 18:42
  • usually it's not working, then you try use jQuery before jquery.js. I assume, you put this script at the footer.
    – Nikit
    Apr 6 at 21:27
  • Yes, Nikit, the code is loading without error now. I am now starting to rearrange and re-title and test my functions with the form_set_messages to replace "$message" Apr 10 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.