Reputation: 36
I have a masked js in some inputs. I'm using them for telephone masked inputs. The problem is that sometimes phone numbers can be 10 digits or 11 digits. I need to change the class if a checkbox is checked. This is what I have.
This is the mask, the ones with "2" are for 11 digits.
$(".phone").mask("(999) 999-9999");
$(".cell").mask("(999) 999-9999");
$(".phone2").mask("(999) 9999-9999");
$(".cell2").mask("(999) 9999-9999");
This is my checkbox:
<input type="checkbox" name="digits" class="digits"/>Check here if you phone numbers have 11 digits (area code included)<br>
And this is my jq (is not working, the class is not changing after click):
$(function(){
$('.digits:checked').click(function(){
if($(this).is(':checked'))
{
$('.phone').addClass('phone2').removeClass('phone');
$('.cell').addClass('cell2').removeClass('cell');
}
});
});
Thanks.
Upvotes: 0
Views: 233
Reputation: 388316
Just changing the assigned class will not change the assigned mask, you need to update the plugin with new options.
There is no need to use 2 different classes, you need to reset the mask.
$(function () {
var $els = $('.phone, .cell').mask("(999) 999-9999");
$('.digits').change(function () {
$els.unmask();
if (this.checked) {
$els.mask("(999) 9999-9999");
} else {
$els.mask("(999) 999-9999");
}
});
});
Demo: Fiddle
Upvotes: 3
Reputation: 38102
You're missing .
to target element with class digits
:
$('.digits:checked').click(function(){
// ^ here ---
Also try to use event delegation if your checkboxes has been added dynamically:
$('body').on('click','digits:checked',function(){
if($(this).is(':checked'))
{
$('.phone').addClass('phone2').removeClass('phone');
$('.cell').addClass('cell2').removeClass('cell');
}
});
Upvotes: 0