I'm sure you have solved this already, but since this is still unanswered (and I stumbled on it) I'll add the solution for future visitors.
Use the correct event
First off, the onKeyPress will actually fire before the typed character has been registered in the input element. So if a user types abc and you do onKeyPress="alert(this.value)" it would alert ab. A better alternative would be onKeyUp, since this would get the last typed character too.
Use the event correctly
Next, the events - your options are:
//inline, not considered "best practice"
<input type="text" name="myinput" id="myinput" onKeyUp="killPObox(this)"/>
//same event as above, but in pure js
document.getElementById('myinput').onkeyup = function (e) {
killPObox(e.target);
};
//or attach an eventListener
document.getElementById('myinput').addEventListener('keyup', function (e) {
killPObox(e.target)
});
All of these should work for the majority of browsers. I would suggest alternative 3, or if you need IE8 support, alternative 2.
The JavaScript, simplified
Your function, killPObox(), should look something like this (using one of the above events):
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
Last but not least..
Finally, a very important part when using event binding, you need to use window.onload(). This is to make sure that both the script and elements that are to be bound are loaded before any code is run.
window.onload = function () {
// my binds, events and calls here
};
An actual working example of all three events:
function killPObox(el) {
if (el.id == 'v65-onepage-shipaddr0' || el.id == 'v65-onepage-shipaddr1' || el.id == 'v65-onepage-shipaddr2') {
if (el.value.substr(0, 4).toUpperCase() === "PO B" || el.value.substr(0, 5) === "P.O. ") {
alert("USA Light cannot ship to P.O. Boxes. Please enter a street address.");
}
}
}
window.onload = function () {
document.getElementById('v65-onepage-shipaddr1').onkeyup = function (e) {
killPObox(e.target);
};
document.getElementById('v65-onepage-shipaddr2').addEventListener('keyup', function (e) {
killPObox(e.target)
});
};
"PO B" or "P.O. " will trigger the alert in all boxes:<br><br>
0. <input type="text" class="quantity" name="v65-onepage-shipaddr0" id="v65-onepage-shipaddr0" onKeyUp="killPObox(this)" />
<br/><br/>
1. <input type="text" class="quantity" name="v65-onepage-shipaddr1" id="v65-onepage-shipaddr1" />
<br/><br/>
2. <input type="text" class="quantity" name="v65-onepage-shipaddr2" id="v65-onepage-shipaddr2" />