How can I show and hide the last 4 numbers of a phone number by replacing it with something like 949XXXX and when you click on it show the rest of the numbers?
I just want to do this with jQuery/JavaScript.
<div id="number" data-last="1234">949<span>XXXX</span></div>
$('#number').click(function() {
$(this).find('span').text( $(this).data('last') );
});
Example: http://jsfiddle.net/4fzaG/
If you want to toggle with each click, do this:
$('#number').toggle(function() {
$(this).find('span').text( $(this).data('last') );
},function() {
$(this).find('span').text( 'XXXX' );
});
Example: http://jsfiddle.net/4fzaG/1/
Or if you don't want to use custom attributes, do this:
<div id="number">949<span>XXXX</span><span style="display:none;">1234</span></div>
$('#number').click(function() {
$(this).find('span').toggle();
});
Example: http://jsfiddle.net/4fzaG/3/
EDIT:
For the sake of graceful degradation, you may want to have the default view show the number, and only obfuscate it if JavaScript is enabled.
<div id="number" data-last="1234">949<span>1234</span></div>
$('#number').toggle(function() {
$(this).find('span').text( 'XXXX' );
},function() {
$(this).find('span').text( $(this).data('last') );
})
.click();
Example: http://jsfiddle.net/4fzaG/4/
Yes, you can do it like that (see jsfiddle as a proof):
jQuery('body').delegate('span[data-replace]', 'click', function(event){
event.preventDefault();
var older_value = jQuery(this).html();
jQuery(this)
.html(jQuery(this)
.attr('data-replace'))
.attr('data-replace',older_value);
});
where phone numbers should be coded like that:
<span data-replace="555-41-23">555-XX-XX</span>
This will show/hide last letters with each click. It binds events to the <body>
(you can change it into some container with the phone numbers) and delegates them to the proper elements on the page, so using AJAX will not be an issue (you will not need to re-attach events).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With