![](/img/trans.png)
[英]How to check if textbox is empty and display a popup message if it is using jquery?
[英]How to check if textbox is empty and display a popup message
我正在为网站编写一些代码,以在文本框提交中的任何参数留空时提醒用户,并且由于某种原因,它不起作用。 我已经尝试了所有方法,但不确定我是否采用了正确的方法。 这是我的 javascript 代码:
let assetInfo = {
asset_tag_no: $(`#asset_tag_no${i}`).val(),
manufacturer: $(`#manufacturer_serial_no${i}`).val(),
descriptions: $(`#description${i}`).val(),
costs: $(`#cost${i}`).val(),
po_no: $(`#p.o._no${i}`).val(),
department_division_head: $(`#department_division_head${i}`).val(),
}
$('#submit').click(function(assetInfo){
if($(assetInfo).val() == ''){
alert('Input can not be left blank');
}
});
这是我的 HTML:
<button type="button" class="btn btn-primary" id='submit'>SUBMIT</button>
有小费吗?
尝试检查assetInfo
object 的具体值,而不是 object 本身。
$('#submit').click(function(assetInfo){
if (assetInfo.asset_tag_no == '' || assetInfo.manufacturer == '' || assetInfo.descriptions == '' || assetInfo.costs == '' || assetInfo.po_no == '' || assetInfo.department_division_head == '') {
alert('Input can not be left blank');
}
});
或者,您可以简单地将required
属性添加到input
元素,然后浏览器可以在输入丢失时以本机方式提醒用户。
<input type="text" name="asset_tag_no" required/>
例如,当您使用 JQuery 通过$('.foo')
获取元素时,它会返回链接到 DOM 的热 object。 但是,当您在 JQuery 元素上调用el.val()
时,您会得到一个原语,因此它不再与该元素的 DOM 值相关联。 因此,您应该调整assetInfo
常量以仅包含元素。 然后,在事件侦听器中需要时获取元素的原始值。 这是你的常量:
let assetInfo = {
asset_tag_no: $(`#asset_tag_no${i}`),
manufacturer: $(`#manufacturer_serial_no${i}`),
descriptions: $(`#description${i}`),
costs: $(`#cost${i}`),
po_no: $(`#p.o._no${i}`),
department_division_head: $(`#department_division_head${i}`),
}
现在,您可以通过在assetInfo
上调用Object.values
来获取元素数组。 之后,我们可以使用Array.prototype.every
方法来检查每个元素的值是否不为空。 您还应该从回调 function 中删除该参数,因为您只能通过其名称访问它。
$('#submit').click(function() {
const allValid = Object.values(assetInfo).every((el) => el.val() != "");
if (!allValid) {
alert('Input can not be left blank');
}
});
如果你在谈论文本框,这里是解决方案:
所以在 HTML 中,你可以在事件期间使用参数调用 Javascript 函数。 您可以使用的 function 称为“onblur”,它会在 window 中的 object 失去焦点时触发。 所以你会输入:
<input type="text" onblur="myFunction(this)" />
<p id="errorMessage" />
然后出于显而易见的原因,我们实际上需要 function。 现在我们将 go:
const errorMessage = document.getElementById('errorMessage')
function myFunction(field) {
if (field === "") {
errorMessage.innerText = "One or more fields were not entered.";
}
}
希望这有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.