MAO-EYE 2015-12-22 02:36 采纳率: 100%
浏览 28

在我的jQuery脚本上需要帮助

I was able to make a dyanamic dropdown subcategory dependent on the selected category which you can see it here.

Now, my problem is that if the category has defined a selected value upon loading which is defined by a REQUEST, just like this (take note on the posted_parent_id request). How can I make a call on my subcategory file(get_child_categories.php?parent_id=6) if my jQuery is like this below:

$(document).ready(function($) {
  var list_target_id = 'list_target'; //first select list ID
  var list_select_id = 'list_select'; //second select list ID
  var initial_target_html = '<option value="">Please select a subcategory...</option>'; //Initial prompt for target select

  $('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option

  $('#'+list_select_id).change(function(e) {
    //Grab the chosen value on first select list change
    var selectvalue = $(this).val();

    //Display 'loading' status in the target select list
    $('#'+list_target_id).html('<option value="">Loading...</option>');

    if (selectvalue == "") {
        //Display initial prompt in target select if blank value selected
       $('#'+list_target_id).html(initial_target_html);
    } else {
      //Make AJAX request, using the selected value as the GET
      $.ajax({url: 'get_child_categories.php?parent_id='+selectvalue,
             success: function(output) {
                //alert(output);
                $('#'+list_target_id).html(output);
            },
          error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status + " "+ thrownError);
          }});
        }
    });
});

Does my question is quite clear? I am still learning this kind of stuff right now. There's something to be defined somewhere within the if (selectvalue == "") statement in case the category dropdown was pre-selected upon loading the page?

  • 写回答

2条回答 默认 最新

  • DragonWar% 2015-12-22 02:43
    关注

    The first thing that you have to do is to move that AJAX functionality out of the .change event.

    Change event fires only when the dwopdown value is changed and if the dropdown renders with a value as selected one, it wont be handled by change event.

    Make it as a separate function and call that on page load and on .change event.

    ** NOT A COMPLETE CODE **

    $(function(){
        var dropdown = $('#'+list_select_id);
        if (dropdown.val() !== "") {
            initiateAJAX(dropdown.val());
        }
        dropdown.change(function() {
            initiateAJAX(this.value);
        }); 
    
        function initiateAJAX(param) {
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构