javascript - jQuery 避免在以编程方式完成时触发更改

标签 javascript php jquery mysql ajax

我有一个基本的发票系统,我们可以在其中选择一个项目(jquery select 2),该项目在更改时会在表格中填写基本价格、每箱单位等。我们可以在保存发票之前更改此价格。

如果我需要编辑这个(保存的)发票(在同一页面和表单中),我会使用 PHP GET 获取 id,然后使用 ajax 获取保存在 mysql 中的发票,以获取项目及其数量,价格等详细信息填写在表格中。

现在的问题是,(在 ajax 之后)当我以编程方式选择选择框(jquery select 2)中的项目时,它会触发 on change 函数(如前所述)并在表单中获取基本价格等,而不是我想以编程方式填充以查看然后更改它的那个。

//Fetch Items
fetchItems()

function fetchItems() {
  $.ajax({
    url: 'https://api.myjson.com/bins/4z7se',
    dataType: "json",
    success: function(items) {
      // Create list of items in select tag
      var toAppend = '';
      $.each(items, function(i, o) {
        toAppend += '<option value="' + o.itemId + '">' + o.newName + '</option>';
      });

      $('#item').append(toAppend);
      $('#item').select2({
        placeholder: "Select an item",
        escapeMarkup: function(markup) {
          return markup;
        }
      })
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert("ERROR:" + xhr.responseText + " - " + thrownError);
    }
  });
}



// On item select, get item details and fill in the table
// --->>> Select first item for this demo to get the details filled (usually  it requests the values from mysql for the selected item)
$('#item').on('change', function() {
  $.ajax({
    url: 'https://api.myjson.com/bins/vjfi',
    dataType: "json",
    success: function(data) {
      // Print item details in respective elements
      $('#itemId').val(data[0]['itemId'])
      $('#size').text(data[0]['size'])
      $('#units_per_ctn').text(data[0]['units_per_ctn'])
      $('#ctn_price').val(data[0]['ctn_price'])
      $('#qty').val('') // Clear qty from previous
      $('#total_price').text('') // Clear total price from previous
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert("ERROR:" + xhr.responseText + " - " + thrownError);
    }
  });
})


// For update purpose, details to be filled in the form
$('#edit').click(function() {
  //var editId = '<?PHP if(isset($_GET['edit '])) { echo $_GET['edit'];}?>';
  var editId = 1 // Lets assume it for this demo
  if (editId > 0) {
    // Get transfer details for this id
    $.ajax({
      url: 'https://api.myjson.com/bins/1iwha',
      dataType: 'json',
      success: function(data) {
        $('table #item').select2().val(data[0]['item_id']).trigger('change')

        // Here is the proble, can't put these values in the input because as soon as select2 change is triggered it fills its own values to the inputs. But I want the following values (returned from mysql in json) to be filled in.
        $('table #ctn_price').val(data[0]['ctn_price'])
        $('table #qty').val(data[0]['qty'])
        $('table #totap_price').val(data[0]['total_price'])
      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert("ERROR:" + xhr.responseText + " - " + thrownError);
      }
    })
  }
})

Here is the Fiddle

最佳答案

您可以使用triggerHandler 并在您的事件监听器 中返回$.ajax 对象。然后您可以链接 .done() 并在 ajax 请求完成后完成您的工作。

// return ajax object
$('#item').on('change', function() {
    return $.ajax({
        /* ... */
    });
});

// chain actions
$('#item').select2().val(val).triggerHandler('change').done(function() {
    // set your values
});

Working example :

//Fetch Items
fetchItems()

function fetchItems() {
  $.ajax({
    url: 'https://api.myjson.com/bins/4z7se',
    dataType: "json",
    success: function(items) {
      // Create list of items in select tag
      var toAppend = '';
      $.each(items, function(i, o) {
        toAppend += '<option value="' + o.itemId + '">' + o.newName + '</option>';
      });

      $('#item').append(toAppend);
      $('#item').select2({
        placeholder: "Select an item",
        escapeMarkup: function(markup) {
          return markup;
        }
      })
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert("ERROR:" + xhr.responseText + " - " + thrownError);
    }
  });
}



// On item select, get item details and fill in the table
// --->>> Select first item for this demo to get the details filled (usually  it requests the values from mysql for the selected item)
$('#item').on('change', function() {
 return $.ajax({
    url: 'https://api.myjson.com/bins/vjfi',
    dataType: "json",
    success: function(data) {
      // Print item details in respective elements
      $('#itemId').val(data[0]['itemId'])
      $('#size').text(data[0]['size'])
      $('#units_per_ctn').text(data[0]['units_per_ctn'])
      $('#ctn_price').val(data[0]['ctn_price'])
      $('#qty').val('') // Clear qty from previous
      $('#total_price').text('') // Clear total price from previous
    },
    error: function(xhr, ajaxOptions, thrownError) {
      alert("ERROR:" + xhr.responseText + " - " + thrownError);
    }
  });
});

// For update purpose, details to be filled in the form
$('#edit').click(function() {
  //var editId = '<?PHP if(isset($_GET['edit '])) { echo $_GET['edit'];}?>';
  var editId = 1 // Lets assume it for this demo
  if (editId > 0) {
    // Get transfer details for this id
    $.ajax({
      url: 'https://api.myjson.com/bins/1iwha',
      dataType: 'json',
      success: function(data) {
        $('table #item').select2().val(data[0]['item_id']).triggerHandler("change").done(function() {
          $('table #ctn_price').val(data[0]['ctn_price'])
          $('table #qty').val(data[0]['qty'])
          $('table #totap_price').val(data[0]['total_price'])
        });
      },
      error: function(xhr, ajaxOptions, thrownError) {
        alert("ERROR:" + xhr.responseText + " - " + thrownError);
      }
    })
  }
})
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<table class="table table-bordered jambo_table">
  <thead>
    <th>Size</th>
    <th>Item Name</th>
    <th>Units/CTN</th>
    <th>CTN Price
      <br><small>(inc GST)</small></th>
    <th>Qty</th>
    <th>Total Price</th>
  </thead>
  <tbody>
    <tr>
      <td id="size"></td>
      <td>
        <select class="form-control" id="item" name="item">
          <option disabled selected>Select an item</option>
        </select>
      </td>
      <td id="units_per_ctn"></td>
      <td>
        <input type="text" class="form-control" id="ctn_price" name="ctn_price" size="10">
      </td>
      <td>
        <input type="text" class="form-control" id="qty" name="qty" size="10">
      </td>
      <td id="total_price"></td>
    </tr>
  </tbody>
</table>

<div>
  Normally item id is received with php get, and the details are fetched with ajax to be filled in this form, (using button for the demo only)<br>
  <button id="edit">Edit Record 1</button>
</div>

关于javascript - jQuery 避免在以编程方式完成时触发更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507233/

相关文章:

javascript - 如何在我的应用程序中注入(inject)模板部分?

php - 不使用 Flash/Silverlight 的 2 人游戏连接

javascript - 在 KineticJS 中缩放到固定点

javascript - 在单个包含服务器中隔离 Node JS "apps"

php - 如何在我的计算机上启用文件夹以允许 php 将文件移动到其中?

javascript - 刷新页面后产品自动添加到购物车

javascript - 在输入文本中书写时保持专注于下拉列表

javascript - jQuery 查找所有以定义的字符串开头并以数字结尾的 id

javascript - 仅假单选按钮 1 选项

javascript - 为什么我的筛子在查找素数方面表现不佳?