Domanda

I have written ajax callback on a textfield and it is called on blur event.

But before It going for ajax callback I want to check a condition that textfield not empty.

So I want,If textfield is not empty then the ajax callback is get called otherwise it should not get called.

Thanks in advance

form_example is my module name

Form control

$form['price_form']['item'] = array(
    '#type' => 'textfield',
    '#title' => 'Item Name?',
    '#size' => 10,
    '#maxlength' => 25,
    '#id' => 'nameId',
    '#required' => TRUE,
    '#ajax' => array(
        // #ajax has two required keys: callback and wrapper.
        // 'callback' is a function that will be called when this element changes.
        'callback' => 'form_example_simplest_callback',
        'wrapper' => 'listDiv',
        'effect' => 'fade',
    ),
    '#autocomplete_path' => 'examples/form_example/item_name_autocomplete_callback',
);

JS Code

(function($){
    $(document).ready(function(){
        alert('Hi, Javascript successfully attached');

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

                // Overwrite beforeSubmit
                Drupal.ajax['nameId'].options.beforeSubmit = function (form_values, element, options) {
                    alert('dsf');
                }
            }
        };
    });
})(jQuery);

I am printing alert for testing.I tried by its name and by its id but not getting alert.I got below alert so js inclusion fine.

alert('Hi, Javascript successfully attached');
È stato utile?

Soluzione

The ajax implementation in the form api lets you specify a 'beforeSubmit' handler that will be run before submission. According to this : http://malsup.com/jquery/form/#options-object if that function returns false the form won't be submitted.

You should be able to add a beforesubmit handler something like:

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

    // Overwrite beforeSubmit
    Drupal.ajax['your_element'].options.beforeSubmit = function (form_values, element, options) {
        // check the textfield isn't blank then return false;
    }
  }
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top