### Get Masked Value Programmatically with $.fn.masked() - jQuery
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
The `$.fn.masked()` method allows you to programmatically get a masked representation of a given value, without needing it to be present in an input field. This is useful for formatting data for display purposes or for validating values against a mask pattern before user input.
```javascript
// Apply mask to an input
$('#phone').mask('(000) 000-0000');
// Get masked version of a different value
var formattedPhone = $('#phone').masked('3488888888');
console.log(formattedPhone); // Output: "(34) 8888-8888"
// Useful for formatting server data before display
var serverData = '19998887777';
var displayValue = $('#phone').masked(serverData);
$('#display-phone').text(displayValue); // Shows: (199) 988-87777
```
--------------------------------
### Get Unmasked Value with $.fn.cleanVal() - jQuery
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
The `$.fn.cleanVal()` method retrieves the raw, unmasked value from an input field that has a mask applied. It strips away all formatting characters, returning only the essential digits or letters. This is crucial for data submission or processing where the formatted string is not desired.
```javascript
// With phone mask applied
$('#phone').mask('(000) 000-0000');
// Displayed value: (123) 456-7890
var rawPhone = $('#phone').cleanVal();
console.log(rawPhone); // Output: "1234567890"
// With currency mask
$('#price').mask('#.##0,00', { reverse: true });
// Displayed value: 1.234,56
var rawPrice = $('#price').cleanVal();
console.log(rawPrice); // Output: "123456"
```
--------------------------------
### Global Configuration with $.jMaskGlobals (JavaScript)
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
Illustrates how to configure default behaviors for all masks using the `$.jMaskGlobals` object. This includes setting default maskable elements, data attribute selectors, watch intervals, and custom translation characters.
```javascript
// Configure global settings before applying masks
$.jMaskGlobals = {
// Elements that can be masked
maskElements: 'input,td,span,div',
// Attribute selector for data-mask
dataMaskAttr: '[data-mask]',
// Auto-apply masks on page load
dataMask: true,
// Interval for watching dynamically added elements (ms)
watchInterval: 300,
// Watch for new inputs matching selector
watchInputs: true,
// Keystroke compensation delay (ms)
keyStrokeCompensation: 10,
// Watch for new data-mask elements
watchDataMask: false,
// Keys to ignore (Tab, Shift, Ctrl, Alt, arrows, etc.)
byPassKeys: [9, 16, 17, 18, 36, 37, 38, 39, 40, 91],
// Default translation characters
translation: {
'0': { pattern: /\d/ }, // Required digit
'9': { pattern: /\d/, optional: true }, // Optional digit
'#': { pattern: /\d/, recursive: true }, // Recursive digit
'A': { pattern: /[a-zA-Z0-9]/ }, // Alphanumeric
'S': { pattern: /[a-zA-Z]/ } // Letter only
}
};
// Add custom translation character globally
$.jMaskGlobals.translation['X'] = { pattern: /[0-9a-fA-F]/ }; // Hexadecimal
// Now use in any mask
$('#hex-color').mask('XXXXXX');
```
--------------------------------
### Callback Options for Mask Events (JavaScript)
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
Explains and demonstrates the use of callback functions (`onChange`, `onKeyPress`, `onComplete`, `onInvalid`) to handle mask-related events. These callbacks allow for custom logic execution based on user input and mask status.
```javascript
$('#phone').mask('(000) 000-0000', {
// Fires when value changes
onChange: function(value, event, element, options) {
console.log('Value changed to:', value);
},
// Fires on each valid key press
onKeyPress: function(value, event, element, options) {
console.log('Key pressed, current value:', value);
},
// Fires when mask is completely filled
onComplete: function(value, event, element, options) {
console.log('Mask complete:', value);
// Enable submit button when complete
$('#submit-btn').prop('disabled', false);
},
// Fires when invalid character is entered
onInvalid: function(value, event, element, invalid, options) {
console.log('Invalid input detected');
console.log('Invalid characters:', invalid);
// invalid is an array: [{p: position, v: value, e: expected_pattern}]
invalid.forEach(function(item) {
console.log('Position:', item.p, 'Value:', item.v, 'Expected:', item.e);
});
}
});
// Example: Form validation with onComplete
$('#credit-card').mask('0000 0000 0000 0000', {
onComplete: function(value) {
validateCardNumber(value.replace(/\s/g, ''));
}
});
```
--------------------------------
### Apply Masks via HTML Data Attributes (HTML)
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
Demonstrates how to apply input masks using HTML's `data-mask` attribute. This method allows for declarative mask configuration directly within the HTML structure.
```html
```
--------------------------------
### Apply Mask with Options - JavaScript
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
Demonstrates how to apply various options to the jQuery Mask Plugin for different input fields. Options include clearing the field if the mask is not completely filled, selecting all text when the field receives focus, and reversing the mask for currency formatting. It also shows combined options and specific configurations for Brazilian phone numbers.
```javascript
// Clear field if mask is not completely filled on blur
$('#required-phone').mask('(000) 000-0000', {
clearIfNotMatch: true
});
// Select all text when field receives focus
$('#auto-select').mask('000-000-0000', {
selectOnFocus: true
});
// Reverse mask for currency (fills from right to left)
$('#currency').mask('#.##0,00', {
reverse: true
});
// Combined options
$('#complete-example').mask('000.000.000-00', {
reverse: true,
clearIfNotMatch: true,
selectOnFocus: true,
placeholder: '___.___.___-__',
translation: {
'0': { pattern: /\d/ }
},
onChange: function(value) {
console.log('CPF changed:', value);
},
onComplete: function(value) {
validateCPF(value);
}
});
// Mask with all options for a Brazilian phone field
$('#br-phone').mask('(00) 00000-0000', {
clearIfNotMatch: true,
selectOnFocus: true,
placeholder: '(__) _____-____',
onComplete: function(phone, e, field, options) {
// Validate phone when complete
if (isValidBrazilianPhone(phone)) {
field.addClass('valid');
}
}
});
```
--------------------------------
### Apply Masks via HTML Data Attributes (JavaScript)
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
Shows how to programmatically apply masks to elements using `$.applyDataMask()`. This is useful for dynamically added content or when specific elements need masking after initial page load.
```javascript
// After dynamically adding masked elements to DOM
$('#container').append('');
// Apply masks to new elements
$.applyDataMask();
// Or apply to specific selector
$.applyDataMask('#container input');
```
--------------------------------
### Apply Mask to Elements with $.fn.mask() - jQuery
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
The `$.fn.mask()` method applies a specified mask pattern to selected input elements. It supports various translation characters for digits, alphanumeric, and letters, and accepts an options object for customization like reverse formatting, placeholders, custom translations, and fallback characters. It can also handle dynamic masks based on input length.
```javascript
// Basic phone number mask
$('#phone').mask('(000) 000-0000');
// Date mask
$('#date').mask('00/00/0000');
// IP address with optional digits
$('#ip').mask('099.099.099.099');
// Currency mask with reverse formatting (right to left)
$('#price').mask('#.##0,00', { reverse: true });
// Mask with placeholder
$('#phone').mask('(000) 000-0000', { placeholder: '(___) ___-____' });
// Custom translation characters
$('#custom').mask('00/YY/0000', {
translation: {
'Y': { pattern: /[0-9*]/ }
}
});
// Mask with fallback character for invalid input
$('#time').mask('00t00', {
translation: {
't': { pattern: /[:,.]/, fallback: ':' }
}
});
// Dynamic mask based on input length (e.g., Brazilian phone numbers)
var phoneMasks = ['0000-00009', '00000-0000'];
var phoneMaskBehavior = function(val) {
return val.replace(/\D/g, '').length === 11 ? phoneMasks[1] : phoneMasks[0];
};
$('#phone').mask(phoneMaskBehavior, {
onKeyPress: function(val, e, field, options) {
field.mask(phoneMaskBehavior(val), options);
}
});
```
--------------------------------
### Remove Mask from Elements with $.fn.unmask() - jQuery
Source: https://context7.com/igorescobar/jquery-mask-plugin/llms.txt
The `$.fn.unmask()` method removes any applied mask from selected elements. It reverts the input to its original unmasked value and cleans up any associated event handlers, placeholders, or maxlength attributes set by the plugin. This is useful for dynamically altering form behavior.
```javascript
// Apply mask initially
$('#phone').mask('(000) 000-0000');
// User types: 1234567890
// Displayed value: (123) 456-7890
// Remove the mask
$('#phone').unmask();
// Value after unmask: 1234567890
// Clean up multiple masked fields
$('.masked-inputs').unmask();
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.