首页 > 解决方案 > jQuery .on("keyup") only fires once after ajax call, does not update if value is changed, using it up update city & state with zipcode

问题描述

This is my jquery with ajax call

$(".zipfield").on("keyup", function(){
            var city = $(this).closest(".addressBlock").find(".cityfield");
            var state = $(this).closest(".addressBlock").find(".statefield");

            if ($(this).val() !== "" && (city.val() === "" || city.val() == null) && (state.val() === "" || state.val() == null) ) {
                $.ajax({
                    method: "POST",
                    url: "<?= $this->baseUrl();?>/search/zip",
                    data: {zip: $(this).val()},
                    complete: function (r, e) {
                        var data = JSON.parse(r.responseText);
                        if (data.status === "OK") {
                            city.val(data.city);
                            state.val(data.state);
                        }
                    }
                });
            }
        });

any suggestions as to how I can get it updated everytime I input a new value for the zipfield

标签: jqueryajax

解决方案


似乎在行中

var city = $(this).closest(".addressBlock").find(".cityfield");
var state = $(this).closest(".addressBlock").find(".statefield");

using$(this).closest(".className")实际上并没有获取元素,因此在您的 ajax 调用之后没有设置它们。

我不相信你可以closest在 jquery 中使用类名。您可能应该找到最接近的tr,或者甚至可以form代替。从那里你可以使用find类名cityfieldstatefield.


推荐阅读