Clear list of form controls Irrespective of control type using jquery

Ankaprasad
Posted by Ankaprasad under jQuery category on | Points: 40 | Views : 212
The below code snippet will helps you in the following scenarios.
1. If you want to clear all controls in the form on button click ( Irrespective of control type)
2. If you want to clear all the control in the popup before it opens.

 $("#btnCreate").click(function () {
var controlIds = ["txtDescription", "txtDuration", "lblErrorMsg", "txtDueDate"]; // array of controls needs to be clear
ClearFormControls(controlIds);
});


    function ClearFormControls(controlIds) {
$.each(controlIds, function (i, cntrl) {
CommonActions.ClearControlByType(cntrl);
})
}


function  ClearControlByType(controlId) {
var ctrlType = $("#" + controlId).get(0).tagName.toLowerCase(); // get control type

if ((ctrlType === "textarea" || ctrlType === "input") && !$("#" + controlId).hasClass('datepicker')) {
$("#" + controlId).val(""); // clear the control value, If control type is Text Box or Text Area
}
else if (ctrlType === "input" && $("#" + controlId).hasClass('datepicker')) {
$("#" + controlId).val(GetCurrentDateTime); // Set current date time, if control is having datepicker css
}
if (ctrlType === "label")
$("#" + controlId).text("");

if (ctrlType === "select")
$("#" + controlId).prop('selectedIndex', 0); // set first value if control type is drop down
}


function  GetCurrentDateTime () {
var todayDate = new Date();
var day = todayDate.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var format = "AM";
var hour = todayDate.getHours();
var min = todayDate.getMinutes();
if (hour > 11) { format = "PM"; }
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (min < 10) { min = "0" + min; }
return month[todayDate.getMonth()] + " " + day + " , " + todayDate.getFullYear() + " " + hour + ":" + min + " " + format;
}

Comments or Responses

Login to post response