如何在Drupal 7中提交AJAX表单之前显示确认框?

时间:2012-09-18 14:31:20

标签: php jquery drupal-7

使用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;
      });

  }
}

2 个答案:

答案 0 :(得分:6)

我找到了解决方案。我们可以通过覆盖beforeSerialize()函数来实现:

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

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

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

      }
   }
 }

答案 1 :(得分:0)

您是否尝试在按钮上添加eventlistener?

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);

编辑:如果你想让你的功能可以重复使用,你可以使用这个:

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);
});
相关问题