lefunction
lefunction

Reputation: 301

How to pass parameters to function using buttons

I have several buttons that use the same implementation but need to pass a different parameter to the function. This if for an mp3 player for context. My idea should be easy to follow, but I cannot get the syntax to work. Hope someone can help.

The button in HTML:

<input id="songToPlay" type="button" value="Click To Play!"/>

Then the javascript onclick call:

document.getElementById('songToPlay').onclick = playSongByThisBand;

The method playSongByThatBand():

function playSongByThisBand() {
    playSongByAnyBand(theIntegerThatRepresentsThisBand);
}

The method playSongByAnyBand(parameter):

function playSongByAnyBand(anIntegerThatRepresentsABand) {
    currentSongIndex=anIntegerThatRepresentsABand;
    //other implementation ect...
}

An alternative approach I tried is:

function playSongByAnyBand(anIntegerThatRepresentsABand) {
    currentSongIndex=anIntegerThatRepresentsABand;
    someObject = function() {other implementation ect...}
}

var functionIWantToExecutre = new playSongByAnyBand(anIntegerThatRepresentsABand)

functionIWantToExecute.someObject();

I cannot get playSongByAnyBand to execute. I could implement each button separately but that is even more redundant that my approach already. Can anyone help me with the syntax to implement multiple buttons this way?

Upvotes: 0

Views: 54

Answers (2)

HBP
HBP

Reputation: 16063

In your button specify the band as a data attribute :

<input id="songToPlay" 
       type="button" 
       value="Click To Play!"
       data-band="bandName" />     

The in your event handler yoiu can fetch it thus :

function playSong (ev) {
   var song = this.id;
   var band = this.getAttribute ('data-band');

   // .. put your play code for band/song rght here

}

Another way of accessing the data-band attribute is using the dataset a relatively new HTML feature now available on most current browsers.

function playSong (ev) {
   var song = this.id;
   var band = this.dataset.band; // Fetches attribute 'data-band'

   // .. put your play code for band/song rght here

}

You can add as many data-xxx attributes as you like for different infos. Each is a string value.

Upvotes: 0

Andrei
Andrei

Reputation: 44680

By Javascript

<input type="button" value="Play" onclick="playSong('param1')" />

function playSong(param) {
    // do something
}

With jQuery

<input type="button" value="Play" id="btnPlay" data-param="param1" />

$("#btnPlay").click(function() {
    var param = $(this).data("param");
    // do something
});

Upvotes: 1

Related Questions