Rob G Rob G - 6 months ago 14
Javascript Question

jQuery change event code not running possible event conflict

Let me start off by saying that this is my second day learning jQuery so I'm very much a beginner.

I've written a document ready function and all components are working except the countryField.change function I wrote. I'm pretty sure the web application already has a change function for this field and I'm not sure if there can be two of the same event on a field. When I say it's not working, I set a breakpoint in the Chrome debugger and it never enters the function.

Maybe I have to temporarily pause the existing event, run my code, then re-enable the default event?

Any help would be appreciated. Thanks.

$(document).ready(function(){
var submitReady = true;
var phoneField = $("p.phone").find("input");
var phoneExt = $("p.Ext").find("input");
var countryField = $("p.country").find("input");
var stateField = $("p.state").find("input");
var provinceField = $("p.Province").find("input");

var regex = /^\([2-9][0-9]{2}\)\s+[2-9][0-9]{2}\-[0-9]{4}$/;

phoneField.mask('(000) 000-0000', {placeholder: "(###) ###-####"});
phoneExt.mask('00000', {placeholder: "#####"});

$('#pardot-form').submit(function() {
// DO STUFF
if (submitReady) {
if (phoneExt.val() != "") {
phoneField.val(phoneField.val() + ' x' + phoneExt.val());
return true;
}
}
else {
return false;
}
});
phoneField.focusout(function() {
if (regex.test($(this).val())) {
submitReady = true;
return true;
}
else {
$(".form-field.phone").after( "<p class='tempError error no-label'>Please Enter a valid phone number: (###) ###-####</p>");
submitReady = false;
}
});
phoneField.focus(function() {
$(".tempError").remove();
});

countryField.change(function() {
phoneField.val("");
provinceField.val("");
stateField.val("");
submitReady = true;
});
});

Answer

You can try

$( "p.country" ).change(function() {
    phoneField.val("");
    provinceField.val("");
    stateField.val("");
    submitReady = true;
});