Mind Chasers Inc.
Mind Chasers Inc.

Multiple Buttons and Actions with a Single Javascript Handler

Here's a way to have multiple HTML buttons call discrete functions on a Web Server with a single Javascript handler. We also show how to handle the call when using the Django Web framework.

X-ray Engineering Services


This brief article presents a solution to having multiple Buttons associated with multiple Web server functions and processing them with a single Javascript handler. For this solution, we make use of the dataset property of an HTMLElement. This property is coded in HTML as data-<attribute> and is retrieved in the common Javascript Button handler using the dataset property of the target element (Button) (see Javascript Listing 2).


Each button has a common class (e.g., button-action), and this class is used to select and add a common Javascript handler for each click. In this example, the data-action attribute defines the function that will be called on the Web server (e.g., via a GET method).

HTML Listing 1
<button class="button-action" data-action="func1">Function 1</button>
<button class="button-action" data-action="func2">Function 2</button>
<button class="button-action" data-action="func3">Function 3</button>


Note that we use our own internal Javascript library referenced to the '$$' symbol. For example:

Javascript Listing 1
function $$(selector, el) {
	if (!el) {
		el = document;
	return el.querySelectorAll(selector);

The Javascript code below creates a click handler for each Button using a common handler. The common handler specifies the desired URL using the function passed in the dataset property (e.g., /funcs/func1).

Javascript Listing 2

$$('.button-action').forEach(function(val, idx, obj) {
	val.addEventListener('click', function(e) {
		var tgt = e.target;
		$.get('/funcs/' + tgt.dataset.action, function(resp) {
			// process reponse

Django / Python

For those using the Django Web Framework on the server, here's what our url pattern looks like:

    url(r'^funcs/(?P<action>[a-z\_]*)', funcs, {}),

Our view function would be called as shown:

def funcs(request, action):

Didn't find an answer to your question? Post your issue below or in our new FORUM, and we'll try our best to help you find a solution.

And please note that we update our site daily with new content related to our open source approach to network security and system design. If you would like to be notified about these changes, then please join our mailing list.

Related articles on this site:

subscribe to mailing list:

Please help us improve this article by adding your comment or question:

your email address will be kept private
authenticate with a 3rd party for enhanced features, such as image upload
previous month
next month