Can I combine two functions into one using Javascript?
- by Melissa
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;
}