Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript passing parameters to function

Rookie question: I have the following JavaScript functions. This works correctly but I don't want to hardcode the strings "Names" and "namesDiv". I want to pass them in as parameters to the getItems().How do I do this?

Edit: The function GetMsg() returns a JSON object: result.

HTML:

<input type="button" onclick="getItems(); return false;" value="Go"/>

JS:

function getItems() {
   loadingMsg();
   GetMsg("Names", null, callback);
}

function callback(result, args){
   clearContainer();
   //do stuff
   document.getElementById("namesDiv").append(foo);
}

function loadingMsg(){
    clearContainer();
    // do stuff
    document.getElementById("namesDiv").append(foo);   
}

function clearContainer(){
    document.getElementById("namesDiv").innerHTML = "";
}
like image 981
K.R. Avatar asked Jul 09 '11 23:07

K.R.


3 Answers

For half of them, it's obvious; you just start passing the parameters to the function:

function loadingMsg(containerID) {
    clearContainer(containerID);
    document.getElementById(itemDiv).append(foo);   
}

function clearContainer(containerID) {
    document.getElementById(containerID).innerHTML = "";
}

callback is a little more complex. We'll turn it into a function returning the callback.

function makeCallback(containerID) {
    function callback(result, args) {
        clearContainer();
        document.getElementById(containerID).append(foo);
    }
    return callback;
}

Now we can call makeCallback to get a callback. We can now write getItems:

function getItems(itemType, containerID) {
   loadingMsg(containerID);
   GetMsg(itemType, null, makeCallback(containerID));
}
like image 132
icktoofay Avatar answered Nov 04 '22 16:11

icktoofay


You can simply:

HTML

<input type="button" onclick="getItems('Names', 'namesDiv'); return false;" value="Go"/>

JS

function getItems(name, div) {
    loadingMsg();
    GetMsg(name, null, function(r, args) { callback(div, r, args); });
}

EDIT: I think I've covered everything...

like image 41
LoveAndCoding Avatar answered Nov 04 '22 17:11

LoveAndCoding


 onclick="getItems('namesDiv', 'Names'); return false;"

and then:

function getItems(param1, param2) {

param1 will be namesDiv and param2 will be Names

This said, I'd recommend you take a look at Unobtrusive JavaScript especially the part that talks about separation of behavior from markup.

like image 31
Pablo Fernandez Avatar answered Nov 04 '22 17:11

Pablo Fernandez