Reputation: 2996
Using Drupal 7 form API, How can I prompt javascript confirm box before submitting an AJAX form? I have tried different possible ways to do this but no success. Here is the code:
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;
}
Here is the Javascript code:
Drupal.behaviors.module = {
attach: function() {
jQuery('#edit-submit').click(function(){
if(!confirm('Are you sure?'))
return false;
});
}
}
Upvotes: 1
Views: 7938
Reputation: 2996
I have found the solution. We can do it by overriding beforeSerialize() function:
Drupal.behaviors.module = {
attach: function() {
Drupal.ajax['edit-submit'].beforeSerialize = function () {
if(confirm('Are you sure?'))
return true;
else
return false;
}
}
}
Upvotes: 7
Reputation: 137
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);
});
Upvotes: 0