首页 > 解决方案 > id为动态时如何调用ajax

问题描述

我有两个带有添加更多按钮的输入字段。如果用户单击“添加”按钮,将显示另外两个具有不同 ID 名称的输入类型文本。

我在第二个输入字段上使用 keyup 功能。如果用户输入任何值,那么它将调用我的 ajax 函数。

现在我的问题是,动态时如何调用 ajax?我的意思是如何将 x 值发送到 ajax?我只是想知道

$("#total_p_price").keyup(function (){));

如何从动态调用?

检查当我第一次输入 number=2 和 total_p_price=10 并计算它并显示 single_price=5。

在此处输入图像描述

哪个是对的。现在我点击添加按钮。这次 number=4 和 total_p_price=100 计算它并显示 single_price=50。这也是正确的,但它也更新了第一个 single_price 字段。

在此处输入图像描述

HTML

<div class="add_row">
  <input type="text" name="" id="number">
  <input type="text" name="" id="total_p_price">
  <input type="text" name="" id="single_price">
  <div class="btn_row add_row_click"> <span> +  </span> Add </div>
</div>

<script>
  $(document).ready(function() {
    var max_fields = 20; //maximum input boxes allowed
    var wrapper = $(".add_row"); //Fields wrapper
    var add_button = $(".add_row_click"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e) { //on add input button click
      e.preventDefault();
      if (x < max_fields) { //max input box allowed
        x++; //text box increment

        $(wrapper).append('<div class="custom_fields"><input type="text" name="" id="number' + x '"><input type="text" name="" id="total_p_price' + x '"><input type="text" name="" id="single_price' + x '"> <div class="btn_row remove_field"> <span> - </span> Remove  </div></div>');
      }
    });

    $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
      e.preventDefault();
      //$(this).parent('custom_fields').remove();
      $(this).closest('.custom_fields').remove();

      x--;
    })
    $("body").on('keyup', 'input[id^=total_p_price]', function() {
      //$('input[id^=single_price]').prop('disabled', true);
      var total_p_price = $(this).val();
      var qty_number = $('input[id^=number]').val();
      $.ajax({
        type: "POST",
        url: baseUrl + "/Customer_control/calculate_total_p_price",
        data: {
          total_p_price: total_p_price,
          qty_number: qty_number
        },
        cache: false,
        success: function(html) {
          //alert(html);
          $('input[id^=single_price]').val(html);
        }
      });
    });
  });
</script>

标签: javascriptjqueryhtmlajax

解决方案


根据我对您的问题的了解,您需要使用事件委托。就像是

$(".add_row").on("keyup","#total_p_price", function (){
    var  total_p_price= $(this).val();
    $.ajax({
        type  : "POST",
        url: baseUrl + "/Customer_control/calculate_total_p_price",
        data: {total_p_price: total_p_price},
        cache : false,
        success: function(html) {
            console.log(html);

        }
     });
});

您需要确保 add_row 元素是 HTML 中的静态元素。


推荐阅读