當用戶在搜索框中輸入某個 ID 時,我正在使用 Onkeyup 觸發。我要解決的一個問題是僅在提交框中有 4 個或更多字符后才運行該函式。例如,當用戶鍵入每個數字時會觸發 ID 號 0949,每次它應該只在 4 位提交結束時觸發時都會回傳一個 GET 請求錯誤。這是控制臺日志的螢屏截圖:
我已經嘗試在我的 onkeyup 函式中包含一個 .length 以及一個失敗的捕獲來嘗試但沒有任何效果,并且它仍然會在每次輸入后觸發。這是我的 JavaScript 代碼:
const getAssetInfo = (assetTag, index) => {
// get the table row that this input is in
$.get("http://localhost:3000/assets/" assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
}); };
$('document').ready(() => {
// Handler to Add New Asset
const table = $("#formTable tbody");
let count = 1;
$('#add').click(() => {
const newRow = `
<tr index="${count}">
<form>
<td><input class="asset-tag" id='asset_tag_no${count}' type='text'
onkeyup = "getAssetInfo(this.value,${count})";
bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required readonly/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required readonly description></textarea></td>
<td><input id='cost${count}' type='value' bottom require readonly/></td>
<td><input id='po_no${count}' type='text' bottom require readonly/></td>
<td><textarea id='remarks${count}' type='text' bottom remarks></textarea></td>
<td><button type="button" index="${count}" class="btn btn-danger btn-remove">X</button></td>
</form>
</tr>
`;
table.append(newRow);
// Handler to Remove New Asset
$('.btn-remove').click(function(){
let index = $(this).attr('index');
$(`tr[index='${index}'`).remove();
});
count ;
});
What is the most optimal way to ensure that only 4 or more digits can be entered into the search box, before it sends a GET request?
uj5u.com熱心網友回復:
您應該能夠使用檢查搜索欄中字符數量的 if 陳述句包裝 getAssetInfo 函式。嘗試像這樣重寫 getAssetInfo 函式:
const getAssetInfo = (assetTag, index) => {
if (assetTag.length >= 4){
// get the table row that this input is in
$.get("http://localhost:3000/assets/" assetTag , (data) => {
// find the `.description` element and set it's value
if (data){
$(`#manufacturer_serial_no${index}`).val(data.serial_no);
$(`#description${index}`).val(data.description);
$(`#cost${index}`).val(data.cost);
$(`#po_no${index}`).val(data.po_no);
}
console.log(data);
})
.fail(() => {
// alert("DONE");
// console.log(index);
$(`#manufacturer_serial_no${index}`).val("");
$(`#description${index}`).val("");
$(`#cost${index}`).val("");
$(`#po_no${index}`).val("");
});
} else {
console.log('not enough characters to call API endpoint');
}
};
在這個 if 陳述句中,我在進行 API 呼叫之前檢查搜索欄是否有 4 個或更多字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456338.html
標籤:javascript html 阿贾克斯
下一篇:來自回圈資料的Ajax呼叫跳過
