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

时间:2016-09-15 09:13:58

标签: javascript php jquery mysql ajax

我有一个基本的发票系统,我们可以在这里选择一个项目(jquery select 2),它在更改中填写基本价格,单位/ ctn等表格。我们可以在保存发票之前更改此价格。

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

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

//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);
      }
    })
  }
})
  

以下是this gist

1 个答案:

答案 0 :(得分:1)

您可以使用triggerHandler并返回$.ajax中的event listener对象。然后你可以链接.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>