0

I had started developing a module in Drupal. I made two form controls: a fieldset and a button. The button calls a javascript function "myphoto_options" when it is click. This function only does an alert function. After executing the called function, the page then immediately refreshes the page. How to prevent the page from reloading?

Below are my codes:

function myid_user_page_form(){  
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE, 
        '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
        '#type' => 'button', 
        '#value' => '...',
        '#attributes' => array(
        'onclick' => "myphoto_options();",),  
    );  
    return $form;
}

Javascript function:

function myphoto_options(){
    alert("Hey");
    return false;
}

Any help would be very much appreciated. Thanks.

2
  • Why you need js? Are you not submitting any data with the form? You may need ajax? Feb 4, 2015 at 9:25
  • Please stop cross-posting your questions both here and on Stack Overflow. Choose the site in the network that's best suited for your question, and only post it there. Thanks
    – Clive
    Feb 4, 2015 at 10:31

1 Answer 1

3

You should do something like this:

function myid_user_page_form() {
    $form = array();
    $form['id'] = array(
      '#type' => 'fieldset',
      '#title' => t('ID Information'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
      '#type' => 'button',
      '#value' => '...',
      '#attached' => array(
        'js' => drupal_get_path('module', 'your_module') . '/js/your_file.js'
      ),
    );
    return $form;
}

Then, add a directory "js" in your module and a js file. In that js file use:

(function ($) {
    Drupal.behaviors.yourModule = {
        attach: function (context, settings) {
            $('#your-element').click(function(e){
                e.preventDefault();

                // Your functionality.

                return false;
            });
        }
    };
})(jQuery);
0