This code takes a 10 digit phone number that's entered and formats it so that all entries to the DB follow the same format. The code works as it is but the problem is that the HTML is generated dynamically and the Id changes. It always starts with "phone" but numbers and dashes are added which breaks the code (ex. phone-59-0-1) The "name" and "class" stay the same but I can't seem to get it to work using those elements.
<form name="registration_form" id="registration_form">
<input type="text" name="phone" id="phone" class="ee-reg-page-questions ee-reg-page-text-input phone" />
</form>
<script>
var x = document.getElementById("phone");
x.addEventListener("blur", formatPhone, true);
function formatPhone() {
var obj = document.getElementById("phone");
var numbers = phone.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:'-'};
obj.value = '';
for (var i = 0; i < numbers.length; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}
</script>
Here's the attempt using getElementByClassName
:
function formatPhone() {
var obj = document.getElementsByClassName("ee-reg-page-questions ee-reg-page-text-input phone")[0];
var numbers = phone.value.replace(/\D/g, ''),
char = {0:'(',3:') ',6:'-'};
obj.value = '';
for (var i = 0; i < numbers.length; i++) {
obj.value += (char[i]||'') + numbers[i];
}
}