I've got some jQuery in an ascx file (Sharepoint WebPart) that responds to a checkbox's changed event, manipulating properties of another control/element based on the state of the checkbox (checked or unchecked, that is the question):
$(document).on("change", '[id$=ckbxEmp]', function () {
var ckd = this.checked;
var $input = $('[id$=txtbxSSNOrITIN]');
if(ckd) $input.data("oldValue", $input.val()); // Remember current value
$input.prop("maxlength", ckd? 4 : 12).css({
background: ckd? 'yellow' : "lightgreen",
width: ckd? 40 : 80
}).val(function(i, v){
// If checked, slice value to four chars:
return ckd && v.length>4 ? v.slice(0,4) : $input.data("oldValue");
});
});
The script above can be run from this fiddle, which is based on an answer I got here
What I yet need to add is custom validation code. If in Employee (SSN) mode (the checkbox is checked), I guess I just need to verify that four chars in the 0..9 subset were entered; if ITIN, though (the checkbox is unchecked), I need a more complicated validation. How do I incorporate that? Do I need to write validation functions and call them from the "val" function? IOW, should this line:
return ckd && v.length>4 ? v.slice(0,4) : $input.data("oldValue");
...be changed to something like:
return ckd && v.length>4 ? getSSN($input.data) : getITIN($input.data);
...and then code up functions like so:
function getSSN(var entry) {
// validate/verify, slice to 4 chars if necessary
}
function getITIN(var entry) {
// validate/verify, slice to 12 if necessary
}
...or what?
UPDATE
Come to think of it, it seems logical (in fact, downright obvious) that I need to create an event handler for the textbox, something like (pseudoscript):
$(document).on("change", '[id$=txtbxSSNOrITIN]', function () {
var $input = $('[id$=txtbxSSNOrITIN]');
var ckbxChecked = "#ckbxEmp".checked;
if (ckbxChecked) {
// validate for SSN, passing $input
}
else {
// validate for ITIN, passing $input
}
});
But "how do I get there from here" is the question...