Can I combine two functions into one using Javascript?

Posted by Melissa on Stack Overflow See other posts from Stack Overflow or by Melissa
Published on 2011-11-19T09:45:48Z Indexed on 2011/11/19 9:50 UTC
Read the original article Hit count: 321

Filed under:
|

I have the following code that I would like to simplify. With javascript and jQuery is there an easy way that I could combine these two functions? Most of the code is the same but I am not sure how I could create a single function that works differently depending on what is clicked.

$(document).ready(function () {
    $('#ListBooks').click(ListBooks);
    $('#Create').click(Create);
});

function Create() {
    var dataSourceID = $('#DataSourceID').val();
    var subjectID = $('#SubjectID').val();
    var contentID = $('#ContentID').val();
    if (dataSourceID && dataSourceID != '00' && 
        subjectID && subjectID != "00" &&
        contentID && contentID != "00")
    {
        var e = encodeURIComponent,
            arr = ["dataSourceID=" + e(dataSourceID),
                   "subjectID=" + e(subjectID),
                   "contentID=" + e(contentID)];
        window.location.href = '/Administration/Books/Create?' + arr.join("&");
    } else {
        alert('Datasource, Subject and Content must be selected.');
    }
    return false;
}

function ListBooks() {
    var dataSourceID = $('#DataSourceID').val();
    var subjectID = $('#SubjectID').val();
    var contentID = $('#ContentID').val();
    if (dataSourceID && dataSourceID != '00' &&
        subjectID && subjectID != "00" &&
        contentID && contentID != "00") {
        var e = encodeURIComponent,
            arr = ["dataSourceID=" + e(dataSourceID),
                   "subjectID=" + e(subjectID),
                   "contentID=" + e(contentID)];
        window.location.href = '/Administration/Books/ListBooks?' + arr.join("&");
    } else {
        alert('Datasource, Subject and Content must be selected.');
    }
    return false;
}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery