I'm creating a site where users click on DIVs that look like a phone dialpad. When there are 3 or 7 characters, I add a hyphen to simulate the appearance of a phone number.
However, when they press the backspace button, it will not subtract the hyphen.
Here's my code with all of the unnecessary code removed:
$(".phone_digit").click(function(e){
var html = "" + $("#input-box").html();
if( event.target.id == "phone_delete" ){
if( ( html.length === 5 ) || ( html.length === 9 ) ) {
$("#input-box").html( html.substr(0, html.length - 2 ) );
} else {
$("#input-box").html( html.substr(0, html.length - 1 ) );
}
html = "" + $("#input-box").html();
} else if ($("#input-box").html().length < 12) {
$("#input-box").html( html + "" + $("#" + event.target.id).html() );
html = "" + $("#input-box").html();
}
if( ( $("#input-box").html().length === 3 ) || ( html.length === 7 ) ) {
$("#input-box").html( $("#input-box").html() + "-");
html = "" + $("#input-box").html();
}
})
One strange thing: if I change the length parameters from "5" and "9" to "4" and "8", the code will subtract past the hyphen. But this isn't ideal because it leaves a dangling hyphen in the #input-box
until you either add or subtract another number.
Here's a fiddle: https://jsfiddle.net/mediocreb/t66jf0t4/3/