0

I was currently developing a module(myid) in Drupal. I made a button(#myid_registrar_button) that must alert whenever it is clicked. Below is my code:

myid.module file:

<?php

    function myid_init() {
        //Jquery Library  
        drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");

        //Custom Javascript             
        drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");   
    }

    function myid_menu()
    {  
        $items = array();

        $items['admin/settings/myid'] = array(
            'title' => 'myid Settings',
            'description' => 'Configuration options for the myid module',
            'page callback' => 'myid_admin_settings',
            'access callback ' => 'user_access',
            'access arguments' => array('administer site configuration'),
        );
        return $items;
    }

    function myid_admin_settings()
    {
        return drupal_get_form('myid_settings_form');
    }

    function myid_settings_form()
    {
        $form = array();
        $form['myid_registrar_button'] = array(
            '#type' => 'button',
            '#value' => '...',       
            '#attributes' => array(
                'id' => 'myid_registrar_button',         
            ), 
        ); 
        return $form;
    }

myid.js file

$(function(){
    $('#myid_registrar_button').on('click', function(e) {
        e.preventDefault(); 
        alert("Eww");             
    }); 
});

Whenever I click a button, it refreshes and doesnt alert something, which is supposedly will not refresh and will alert "Eww". It seems that the onclick event is not captured.The console throws no error. Where am I missing?

0

You shouldn't be adding JQuery like that. It's automatically included in core, so you don't need to include it yourself. To stay up with the latest JQuery version, install the jQuery Update module.

For your JS file, this should work:

(function ($) {
    Drupal.behaviors.myid.registrar_button = {
        attach: function (context, settings) {
            $('#myid_registrar_button').on('click', function(e) {
                e.preventDefault(); 
                alert("Eww");             
            }); 
        }
    };
})(jQuery);
| improve this answer | |
  • I edited ur code from Drupal.behaviors.myid.registrar_button to Drupal.behaviors.myid_registrar_button . Thanks, I'll keep your advice. – user34776 Mar 24 '15 at 7:45
  • You don't want to do that. Drupal.behaviors holds all the code to run on page load. You can change it to Drupal.behaviors.myid_registrar_button, but make sure it's under Drupal.behaviors. – dwcdev Mar 24 '15 at 7:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy