Reputation: 22395
I have an html input for an optional phone number, along with 2 radio inputs (Leave Message, Dont Leave Message):
<input type="text" class="input-medium phoneNum2" name="secondaryPhone" id="secondaryPhone" onkeypress="toggleRadio(this)" onblur="toggleRadio(this)" placeholder="703-555-1010" value="<cfoutput>#session.secondaryPhone#</cfoutput>" />
Notice I have two events running (deleting one of them yields the same issue, having both helps out, but I'd rather have only one event unless necessary).
The scenario here is: The second somebody starts typing into the input, it checks to see if one of the radio buttons is already checked. If not, default select yes. If for some reason they delete the phone number as they do not want to give it, both radio buttons should be de-selected (only the onblur
works there). And if the "Don't Leave Message" is selected BEFORE the user starts typing, it should not default to yes.
Here is the JavaScript:
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
if (x.value.length > 0 && !z.checked) y.checked = true;
}
Now for the issue: The default option yes is only triggered when I type in 2 characters, instead of the desired 1 (almost like a delay in the code?). If I have "No" Selected before I start typing, it defaults to yes once I type in the 2 characters. Likewise for reverse, nothing is "de-selected" when there are 0 characters during the onkeypress
event, only when the input loses focus during the onblur
event.
Am I using the wrong events? Is there a logic flaw? There are no error messages, and no, I cannot use jQuery here, so please don't give me jQuery answers or the usual "Why no jQuery?" (I love jQuery I simply have reasons I cannot use it).
Edit: I also tried ordering the JavaScript like this, to no avail.
function toggleRadio(x) {
y = document.getElementById("contactSecondaryYes");
z = document.getElementById("contactSecondaryNo");
if (x.value.length > 0 && !z.checked) y.checked = true;
if (x.value.length < 1) {
y.checked = false;
z.checked = false;
}
}
Basically I want to know why the code is acting like there is a delay, and is there a way to fix it?
Upvotes: 0
Views: 895