dpno17028 2014-11-02 19:55
浏览 56
已采纳

在从Javascript函数创建的选择框上使用JQuery运行AJAX请求

I have a php form that performs a series of AJAX requests after a user clicks a select box. I am trying to find a way of duplicating this series of select boxes with the associated AJAX functions using a button.

This form has a select box where a user can select a country. This then sends an ajax request that creates a select box where a user can select regions in that country and this sends an ajax request that creates a select box where a user can select prefectures in that region and this sends a final ajax request that creates a select box where a user can select a city in that prefecture. That part works with the following code.

<?php <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
//Connect to Database require 'connections_pdo.php'; $country = $conn->prepare("SELECT DISTINCT country FROM country ORDER BY country ASC"); $country->execute(array( 'country' )); $country->setFetchMode(PDO::FETCH_ASSOC); echo "
<html>

<head>
  <script src='jquery-ui-1.10.2.custom/js/jquery-1.9.1.js'></script>
  <script src='jquery-ui-1.10.2.custom/js/jquery-ui-1.10.2.custom.js'></script>
  <script src='select_area.js?date=" . $date . "'></script>
</head>"; //Form To Select Geographic Area echo "

<body>
  <form name='input' id='input' action='article_insert_2.php' enctype='multipart/form-data' method='post'>"; //Geographic Area echo "
    <table>
      <tr>
        <th>
          <div id='country'>Country
            <br />
            <select class='country' name='country[]' id='country_1'>
              <option value=''></option>"; $i = 0; while ($row = $country->fetch()) { if ($i == 0) { $countries = array(); } else { } array_push($countries, $row['country']); $i++; } foreach ($countries as $d) { echo "
              <option value='" . $d . "'>" . $d . "</option>"; } echo "</select>
            <br/>
          </div>
          <button id='add_country'>Add Country</button>
        </th>
        <th>
          <div id='region'></div>
        </th>
        <th>
          <div id='prefecture'></div>
        </th>
        <th>
          <div id='sub_prefecture'></div>
        </th>
        <th>
          <div id='city'></div>
        </th>
      </tr>
    </table>"; //Submit echo "
    <input type='submit' value='Submit'>
  </form>"; ?>

This is the Javascript with the AJAX code needed to create the select boxes.

$(document).ready(function() {

  //AJAX request on Country select box appends a Region select box
  //then an AJAX request on Region select box brings appends a Prefecture select box
  //then an AJAX request on Prefecture select box appends a City Select Box
  $('.country').on("change", function() {
    var ids = this.id.split("_");
    var id = ids[1];
    var country = $("#country_" + id).val();
    $.ajax({
      url: 'region.php?t=' + Math.random(),
      type: "POST",
      data: {
        country: country,
        id: id
      },
      success: function(result) {
        $("#region").append(result);
        $(document).ready(function() {
          $('.region').on("change", function() {
            var ids = this.id.split("_");
            var id = ids[1];
            var country = $("#country_" + id).val();
            var region = $("#region_" + id).val();
            $.ajax({
              url: 'prefectures.php?t=' + Math.random(),
              type: "POST",
              data: {
                country: country,
                region: region,
                id: id
              },
              success: function(result) {
                $("#prefecture").html(result);
                $(document).ready(function() {
                  $('#prefecture_1').on("change", function() {
                    var ids = this.id.split("_");
                    var id = ids[1];
                    var country = $("#country_" + id).val();
                    var region = $("#region_" + id).val();
                    var prefecture = $("#prefecture_" + id).val();
                    $.ajax({
                      url: 'cities.php?t=' + Math.random(),
                      type: "POST",
                      data: {
                        country: country,
                        region: region,
                        prefecture: prefecture,
                        id: id
                      },
                      success: function(result) {
                        $("#city").html(result);
                      }
                    })
                  })
                })
              }
            })
          })
        })
      }
    })
  })
 
})

However, I want to create a button with a function that duplicates those select boxes. At present I have the following code that will append another select box with the class country to my country div tag. However, the AJAX functions associated with the onchange event for the select boxes with the class country do not work with this new select box.

   //Function to append additional select boxes with all countries to the country Div tag
  var country_id = 2;
  $('#add_country').on("click", function(e) {
    e.preventDefault();
    var options = $('#country_1 option');
    var country_select = "<select class='country' name = 'country[]' id='country_" + country_id + "'>";
    $.map(options, function(option) {
      country_select += "<option value='" + option.value + "'>" + option.value + "</option>";
    })
    country_select += "</select><br />";
    $('#country').append(country_select);
    country_id++;
  })

Please let me know if I need to clarify anything or add additional code.

  • 写回答

1条回答 默认 最新

  • dtbiszu7724 2014-11-02 20:12
    关注

    To make your event handler work for elements added after the page loads you need to use Event delegation:

    $('#country').on("change", ".country", function() {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题