docwho
docwho

Reputation: 73

Do nothing, if dropdown form indicated isn't present

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

Answers (2)

Esko
Esko

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

j08691
j08691

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

Related Questions