Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Show and hide last 4 numbers of a phone number

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.

like image 234
Morne Zeelie Avatar asked Dec 07 '22 21:12

Morne Zeelie


2 Answers

<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/

like image 59
user113716 Avatar answered Dec 31 '22 13:12

user113716


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).

like image 23
Tadeck Avatar answered Dec 31 '22 11:12

Tadeck