1

使用 Drupal 7 表单 API,如何在提交 AJAX 表单之前提示 javascript 确认框?我尝试了不同的可能方法来做到这一点,但没有成功。这是代码:

function create_list_form($form, &$form_state) {

  $form['list_name'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'List Name'
    '#attributes' => array()
  );

  $form['list_desc'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'List Desc'
    '#attributes' => array()
  );

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#attributes' => array('class' => array('use-ajax-submit')),            
        '#value' => 'Create List'
      );


  return $form;
}

这是Javascript代码:

Drupal.behaviors.module = {
  attach: function() {

       jQuery('#edit-submit').click(function(){
          if(!confirm('Are you sure?'))
              return false;
      });

  }
}
4

2 回答 2

7

我找到了解决方案。我们可以通过重写 beforeSerialize() 函数来做到这一点:

 Drupal.behaviors.module = {
  attach: function() {  

     Drupal.ajax['edit-submit'].beforeSerialize = function () {  

          if(confirm('Are you sure?'))
              return true;
          else
              return false;

      }
   }
 }
于 2012-09-24T10:23:02.450 回答
0

Did you try to add an eventlistener on your button?

function show_confirmation() {
    if (confirm("Do you want to submit?")){
        // here you can do something before it gets submitted
    } else {
        // return false prevents the form from submitting
        return false;
    }
}
var button = document.getElementById('button_name');
button.addEventListener('click', show_confirmation);

Edit: You can use this one if you want to make your function re-usable:

function your_callback_func() {
    // This could be any code for example your AJAX code etc
}

function show_confirmation(your_callback_func) {
    if (confirm("Do you want to submit?")){
        your_callback_func()
    } else {
        // return false prevents the form from submitting
        return false;
    }
}
var button = $('#button_name');
button.click(function() {
    show_confirmation(your_callback_func);
});
于 2012-09-18T15:23:52.563 回答