Reputation: 73
I have a script that redirects a user based upon the selection they make in a dropdown form. The script works fine except for when there is no form present. When a the form is NOT present, it redirects users. I think this is because of how the code is written. It says, if US is not selected, redirect. Since there is no dropdown form, there is no US selected. How can I rewrite this to not redirect, if no shipping-country is present?
$(document).ready(function(){
var una = "ok";
var checkIfUS = function() {
if(($("#shipping-country").val() != "US") &&(una=="ok")){
iCheckout.insertForm();
$("#iCheckoutForm").submit();
}
};
checkIfUS(); // check if it should redirect after dom load
$("#shipping-country").change(function(event){
checkIfUS(); // check if it should redirect on form change
});
});
Upvotes: 0
Views: 59
Reputation: 4207
You could just raise the change-event with jQuery, if the element doesn't exist, it will not be raised:
$(document).ready(function() {
var una = "ok";
$("#shipping-country").on("change", function(event){
if($(this).val() != "US" && una=="ok") {
iCheckout.insertForm();
$("#iCheckoutForm").submit();
}
}).change();
});
Upvotes: 1
Reputation: 207901
Change your if condition to:
if($("#shipping-country").length && ($("#shipping-country").val() != "US") &&(una=="ok")){
By adding $("#shipping-country").length
your condition will only continue if the element exists.
Upvotes: 1