当用户在搜索框中输入某个 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?
您应该能够使用检查搜索栏中字符数量的 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 个或更多字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句