I can't seem to add these event listeners at page load reliably. Some of the listeners work from the beginning, but others only work after a few clicks. What might be wrong? Could the problem be that I'm mixing native JS with jQuery?
<script>
$(document).ready(function() {
function resetValidation() {
jQuery('#contact-form').validate().resetForm();
};
function resetFormFields() {
document.getElementById('contact-form').reset();
};
function removeValidationClasses() {
jQuery('.control-group').removeClass('success').removeClass('error');
};
function changeHeaderToAdd() {
document.getElementById('contactModalLabel').innerText = 'Add Contact';
};
function changeHeaderToUpdate() {
document.getElementById('contactModalLabel').innerText = 'Update Contact';
};
function clearContactId() {
document.getElementById('contactId').value = '';
};
var ab = document.getElementById('addContactBtn');
if (ab.addEventListener) {
ab.addEventListener('click', resetValidation, false);
ab.addEventListener('click', resetFormFields, false);
ab.addEventListener('click', removeValidationClasses, false);
ab.addEventListener('click', changeHeaderToAdd, false);
ab.addEventListener('click', clearContactId, false);
} else {
ab.attachEvent('onclick', resetValidation);
ab.attachEvent('onclick', resetFormFields);
ab.attachEvent('onclick', removeValidationClasses);
ab.attachEvent('onclick', changeHeaderToAdd);
ab.attachEvent('onclick', clearContactId);
};
var ub = document.getElementById('updateContactBtn');
if (ub.addEventListener) {
ub.addEventListener('click', resetValidation, false);
ub.addEventListener('click', resetFormFields, false);
ub.addEventListener('click', removeValidationClasses, false);
ub.addEventListener('click', changeHeaderToUpdate, false);
} else {
ub.attachEvent('onclick', resetValidation);
ub.attachEvent('onclick', resetFormFields);
ub.attachEvent('onclick', removeValidationClasses);
ub.attachEvent('onclick', changeHeaderToUpdate);
};
});
</script>
Solved!
The JS was fine. However, since #updateContactBtn
was created dynamically (one for each contact on the page), the problem was caused by the presence of nonunique id's. Only the first instance of #updateContactBtn
worked.
I changed #updateContactBtn
to .updateContactBtn
.