JQuery 分层自动完成,不为下一层设置数据

发布于 2024-11-02 18:13:39 字数 2256 浏览 8 评论 0原文

我正在运行州和省名称的自动完成功能。我想将状态缩写传递给下一个自动完成级联。我创建了一个隐藏输入,我想在选择州名称时将其设置为缩写,然后我将选择缩写以在下一层自动完成中使用,以将城市查询仅限于一个州。在前面的步骤中,我在 .ajax 数据选项中设置了国家/地区单选按钮设置州限制,因此您可以(通常)看到我想要在此州/城市层执行的操作。我已经尝试了几件事,做了很多 Google 搜索和阅读 jQuery 书籍,但我需要一些帮助。 stateProvince 输入框会自动完成并选择完整的州名称。隐藏输入不会使用缩写设置。警报为空。我不确定 ajax 成功或 ajax 选择功能。如何将缩写(而不是名称)作为隐藏输入的值?然后我如何在下一层的 .ajax 数据选项中选择它?这是相关代码。

选定的不带标签符号的 HTML:

输入 type="text" id="stateProvince" name="stateProvince" size="50" maxlength="50" 输入类型=“隐藏”ID=“隐藏状态”名称=“隐藏状态”

自动完成源ajax;

    $("#stateProvince").autocomplete
    ({
        source: function( request, response )
        {                           
            //Pass the selected country to the php to limit the stateProvince selection to just that country  
            $.ajax(
            {
                url: "getStateProvince.php",
                data: {
                        term: request.term, 
                        country: $('input[name=country]:checked').val()    //Pass the selected country to php
                      },       
                type: "POST", 
                dataType: "json",
                success: function( data )
                {                                          
                    response( $.map( data, function( item )
                    {
                        return{                                   
                                label: item.stateName,
                                value: item.name,
                                abbrev: item.stateAbbrev                                                                   
                               }
                    }));
                },
                select: function( event,ui )
                {
                $(this).val(ui.item.value);
                $("#hiddenState").$(this).val(ui.item.abbrev);
                }
            });
            alert('|' + $("#hiddenState").val() + '|2nd');  //doesn't trigger here; shows no content when placed in the next tier Autocomplete              
        },           
        minLength: 2
    });

从 php 返回的 JSON 示例:

[{"stateName":"Alabama","name":"Alabama","stateAbbrev":"AL"},{"stateName":"Alaska","name":"Alaska", “stateAbbrev”:“AK”}]

I have an Autocomplete for state and province names running. I want to pass the state abbreviation to the next cascade of Autocomplete. I created a hidden input and I want to set it to the abbreviation when the state name is selected, then I'll select the abbreviation for use in the next tier Autocomplete to limit the city query to one state only. At a prior step, I have country radio buttons setting a state limit in the .ajax data option, so you can see (generally) what I want to do in this state/city tier. I've tried several things, done a lot of Google searching and reading jQuery books, but I need some help. The stateProvince input box autocompletes and selects the full state name. The hidden input does not get set with the abbreviation. The alert is empty. I'm not sure about either the ajax success or the ajax select functions. How do I get the abbreviation (not the name) to be the value of the hidden input? and how can I then select it in the next tier's .ajax data option? Here is the relevant code.

selected HTML without tag symbols:

input type="text" id="stateProvince" name="stateProvince" size="50" maxlength="50"
input type="hidden" id="hiddenState" name="hiddenState"

Autocomplete source ajax;

    $("#stateProvince").autocomplete
    ({
        source: function( request, response )
        {                           
            //Pass the selected country to the php to limit the stateProvince selection to just that country  
            $.ajax(
            {
                url: "getStateProvince.php",
                data: {
                        term: request.term, 
                        country: $('input[name=country]:checked').val()    //Pass the selected country to php
                      },       
                type: "POST", 
                dataType: "json",
                success: function( data )
                {                                          
                    response( $.map( data, function( item )
                    {
                        return{                                   
                                label: item.stateName,
                                value: item.name,
                                abbrev: item.stateAbbrev                                                                   
                               }
                    }));
                },
                select: function( event,ui )
                {
                $(this).val(ui.item.value);
                $("#hiddenState").$(this).val(ui.item.abbrev);
                }
            });
            alert('|' + $("#hiddenState").val() + '|2nd');  //doesn't trigger here; shows no content when placed in the next tier Autocomplete              
        },           
        minLength: 2
    });

JSON example returned from php:

[{"stateName":"Alabama","name":"Alabama","stateAbbrev":"AL"},{"stateName":"Alaska","name":"Alaska","stateAbbrev":"AK"}]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一枫情书 2024-11-09 18:13:39

你差不多已经明白了!我看到以下问题:

  1. selectautocomplete 小部件上的事件。您现在的代码将 select 定义为 $.ajax({...}); 调用的选项。

  2. 失败的alert语句位于自动完成小部件的source函数内。我猜它会在你开始打字后立即弹出。它为空的原因是它不在 select 函数内部(并且它发生在 AJAX 调用成功返回之前)。

您可以按如下方式调整代码:

$("#stateProvince").autocomplete
({
    source: function( request, response )
    {                           
        //Pass the selected country to the php to limit the stateProvince selection to just that country  
        $.ajax(
        {
            url: "getStateProvince.php",
            data: {
                    term: request.term, 
                    country: $('input[name=country]:checked').val()    //Pass the selected country to php
                  },       
            type: "POST", 
            dataType: "json",
            success: function( data )
            {                                          
                response( $.map( data, function( item )
                {
                    return{                                   
                            label: item.stateName,
                            value: item.name,
                            abbrev: item.stateAbbrev                                                                   
                           }
                }));
            }
        });             
    },      
    select: function( event,ui )
    {
        $(this).val(ui.item.value);
        $("#hiddenState").val(ui.item.abbrev);
        alert('|' + $("#hiddenState").val() + '|2nd');  //doesn't trigger here; shows no content when placed in the next tier Autocomplete 
    },     
    minLength: 2
});

记下 alert 语句和 select 事件处理程序的位置。

You've almost got it! I see the following problems:

  1. select is an event on the autocomplete widget. Your code as it is right now is defining select as an option to the $.ajax({...}); call.

  2. The alert statement that's failing is inside the source function to the autocomplete widget. I'm guessing it pops up right after you start typing. The reason it's empty is because it is not inside the select function (and it takes place before your AJAX call comes back successfully).

You can tweak your code as follows:

$("#stateProvince").autocomplete
({
    source: function( request, response )
    {                           
        //Pass the selected country to the php to limit the stateProvince selection to just that country  
        $.ajax(
        {
            url: "getStateProvince.php",
            data: {
                    term: request.term, 
                    country: $('input[name=country]:checked').val()    //Pass the selected country to php
                  },       
            type: "POST", 
            dataType: "json",
            success: function( data )
            {                                          
                response( $.map( data, function( item )
                {
                    return{                                   
                            label: item.stateName,
                            value: item.name,
                            abbrev: item.stateAbbrev                                                                   
                           }
                }));
            }
        });             
    },      
    select: function( event,ui )
    {
        $(this).val(ui.item.value);
        $("#hiddenState").val(ui.item.abbrev);
        alert('|' + $("#hiddenState").val() + '|2nd');  //doesn't trigger here; shows no content when placed in the next tier Autocomplete 
    },     
    minLength: 2
});

Note the location of the alert statement and the select event handler.

秋日私语 2024-11-09 18:13:39

以下是自动完成的 2d 州级和 3d 城市级的代码。

    //2d tier - stateProvince: autocomplete selection
    //set the country for the 2nd tier to select stateProvince from only the country selected in the 1st tier         
    $("#stateProvince").autocomplete
    ({ 
        source: function( request, response )
        {                          
            //Pass the selected country to the php query manager to limit the stateProvince selection to just that country                                               
            $.ajax(
            { 
                url: "getStateProvince.php",
                data: {
                        term: request.term,   
                        country: $('input[name=country]:checked').val()    //Pass the selected country to php
                      },        
                type: "POST",  // a jQuery ajax POST transmits in querystring format in utf-8
                dataType: "json",   //return data in json format                                                                                                                                                        
                success: function( data ) 
                {                                           
                    response( $.map( data, function( item ) 
                    {
                        return{                                    
                                label: item.stateName,
                                value: item.name,
                                abbrev: item.stateAbbrev                                                                    
                               }
                    }));
                }
            });
        },
        select: function( event,ui )
        {
            $(this).val(ui.item.value);
            $("#hiddenState").val($(this).val(ui.item.abbrev));
            //alert('|' + $("#hiddenState").val() + '|1st');  //shows [object,Object] 
        },      
        minLength: 2
    });

    //3d tier - city: autocomplete selection  //                        
    $( "#city" ).autocomplete
    ({                 
        source: function( request, response ) 
        {              
            $.ajax(
            {
                url: "http://ws.geonames.org/searchJSON",
                dataType: "jsonp",
                data: 
                {
                    featureClass: "P",
                    country: $('input[name=country]:checked').val(),
                    adminCode1: $("#hiddenState").val(), //"AK", //works-delivers only Alaska towns.
                    style: "full",
                    maxRows: 10,
                    name_startsWith: request.term
                },

                success: function( data ) 
                {
                    response( $.map( data.geonames, function( item ) 
                    {
                        return{
                                label: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "")
                               }
                    }));
                }
            });
        },
        select: function( event, ui ) 
            {
                $(this).val(ui.item.value);
                //ui.item.option.selected = true;
                //self._trigger( "selected", event, {item: ui.item.option});
            },  //combo box demo uses this to bar illegal input. Other things are needed also. item.option is not defined
        minLength: 2,


        open: function() 
        {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() 
        {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }
    });

Here is the code for both the 2d state tier and 3d city tier of the Autocomplete.

    //2d tier - stateProvince: autocomplete selection
    //set the country for the 2nd tier to select stateProvince from only the country selected in the 1st tier         
    $("#stateProvince").autocomplete
    ({ 
        source: function( request, response )
        {                          
            //Pass the selected country to the php query manager to limit the stateProvince selection to just that country                                               
            $.ajax(
            { 
                url: "getStateProvince.php",
                data: {
                        term: request.term,   
                        country: $('input[name=country]:checked').val()    //Pass the selected country to php
                      },        
                type: "POST",  // a jQuery ajax POST transmits in querystring format in utf-8
                dataType: "json",   //return data in json format                                                                                                                                                        
                success: function( data ) 
                {                                           
                    response( $.map( data, function( item ) 
                    {
                        return{                                    
                                label: item.stateName,
                                value: item.name,
                                abbrev: item.stateAbbrev                                                                    
                               }
                    }));
                }
            });
        },
        select: function( event,ui )
        {
            $(this).val(ui.item.value);
            $("#hiddenState").val($(this).val(ui.item.abbrev));
            //alert('|' + $("#hiddenState").val() + '|1st');  //shows [object,Object] 
        },      
        minLength: 2
    });

    //3d tier - city: autocomplete selection  //                        
    $( "#city" ).autocomplete
    ({                 
        source: function( request, response ) 
        {              
            $.ajax(
            {
                url: "http://ws.geonames.org/searchJSON",
                dataType: "jsonp",
                data: 
                {
                    featureClass: "P",
                    country: $('input[name=country]:checked').val(),
                    adminCode1: $("#hiddenState").val(), //"AK", //works-delivers only Alaska towns.
                    style: "full",
                    maxRows: 10,
                    name_startsWith: request.term
                },

                success: function( data ) 
                {
                    response( $.map( data.geonames, function( item ) 
                    {
                        return{
                                label: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name + (item.adminName2 ? ", " + item.adminName2 : "") + (item.adminName1 ? ", " + item.adminName1 : "")
                               }
                    }));
                }
            });
        },
        select: function( event, ui ) 
            {
                $(this).val(ui.item.value);
                //ui.item.option.selected = true;
                //self._trigger( "selected", event, {item: ui.item.option});
            },  //combo box demo uses this to bar illegal input. Other things are needed also. item.option is not defined
        minLength: 2,


        open: function() 
        {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() 
        {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文