gpt4 book ai didi

jquery - 在 Rails 中加载表单后调用 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-01 05:57:21 25 4
gpt4 key购买 nike

我正在添加表单上下拉列表更改时加载下拉值。但在编辑时,如果选择了这两个值,则必须填充这两个值。现在我想这样做:-

我制作了一个 JavaScript 函数,它将获取第一个下拉列表的选定值并执行 ajax 调用并获取第二个下拉列表的数据。

现在的问题是我应该何时以及如何调用该函数?

一种方法是在表单加载后调用该函数。这就是我需要您帮助的地方。如何在表单加载后调用该函数?

这是函数:

function getTypeOfLocation(munId){
$('#cad_type_of_location_id > option').remove();
$.getJSON("/cad/get_typeoflocation?" + 'id=' + munId, function(data) {

if (data.length != 0) {
var opt = $('<option />'); // here we're creating a new select option with for each city
opt.val(data[0].id);
opt.text(data[0].name);
$('#cad_type_of_location_id').append(opt); //here we will append these new select options to a dropdown with the id 'cities'

} else {
var opt = $('<option value=""> No Data </option>');
$('#cad_type_of_location_id').append(opt);
}
});
}

最佳答案

您可以使用 on() 委托(delegate) change 处理程序,以便在运行代码时 select 不需要存在。基本上,这意味着您可以在表单存在之前在页面加载代码中创建委托(delegate)更改处理程序。

$(document).on( 'change', '#ID_of_select', function(){
getTypeOfLocation( $(this).val() );
})

关于jquery - 在 Rails 中加载表单后调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14294623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com