Using same dialog for adding and editing
I have written a code for adding data with a dialog, but now I need a separate button that calls the same dialog for editing that data. How can I change buttons within the dialog when called from the #edit-user button.
So I need:
1.button:#create-user ---> SAVE, CANCEL (this one already works)
2.button:#edit-user ---> UPDATE, DELETE, CANCEL
- $(function () {
var dialog, form,
name = $("#name"),
birthdate = $("#student-datepicker"),
allFields = $([]).add(name).add(birthdate),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function checkDate(o, n) {
if (o.val() == "") {
o.addClass("ui-state-error");
updateTips(n);
return false;
}
else {
return true;
}
}
function addStudent() {
var data = {
'action': 'add_student',
'name': name.val(),
'birth': birthdate.val(),
'add-student': true
};
var valid = false; // po defaultu treba da bude false dok se ne utvrdi da je true
allFields.removeClass("ui-state-error");
valid = checkLength(name, "name", 4, 16);
valid = valid && checkRegexp(name, /^[A-Za-z\d=#$%@_ -]+$/i, "Name may consist of a-z, and at least 4 letters.");
valid = valid && checkDate(birthdate, "Date must be set");
if (valid) {
$.post(ajaxurl, data, function (studentId) {
//Ovo je asinhrona funkcija koja se poziva ako je ajax uspesno odradjen
id = studentId;
$("#the-list").append("<tr>" +
"<td><a id=\"edit-student\" title=\"Edit or Delete Student information\" href=\"#\" data-id=\"" + id + "\">Edit</a>" + "</td>" +
"<td>" + name.val() + "</td>" +
"<td>" + birthdate.val() + "</td>" +
"</tr>");
dialog.dialog("close");
});
} else {
}
}
dialog = $("#dialog-form").dialog({
show: {effect: "fade", duration: 200},
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Submit": addStudent,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[ 0 ].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addStudent();
});
$("#create-user").button().on("click", function () {
dialog.dialog("open");
});
});
$(function () {
$("#student-datepicker").datepicker({dateFormat: 'yy-mm-dd'});
});