如何在 JavaScript 循环中发出一次警报
code :在下面显示的代码中,警报消息不断循环,直到语句结束。我需要一个警报语句仅警报一次。如何实现这一点?
这里检查复选框的输出,如果未选中,则显示未定义
for(j=1;j<=numOflimit;j++)
{
var select = $("input[name=select+j]:checked").val();
//alert (select);
//$check='undefined';
if(select==undefined)
{
alert ("Please select atleast one product");
}
else
{
var postData = $("form").serialize();//"product_name="+product_name+"&barcode="+barcode+"&Quantity"+Quantity;
$.ajax
({
type: 'POST',
url: 'http://localhost/example/index.php/castoutput',
data: postData,
success: function(html) {
// alert(html);
$('#cast2').html(html);
}
});
}
}
code : In the below code shown, the alert message keeps on looping till the end of the statement.I need a alert statement to alert only once.How to achieve this?
Here it is checking the output of a checkbox if its not selected it shows undefined
for(j=1;j<=numOflimit;j++)
{
var select = $("input[name=select+j]:checked").val();
//alert (select);
//$check='undefined';
if(select==undefined)
{
alert ("Please select atleast one product");
}
else
{
var postData = $("form").serialize();//"product_name="+product_name+"&barcode="+barcode+"&Quantity"+Quantity;
$.ajax
({
type: 'POST',
url: 'http://localhost/example/index.php/castoutput',
data: postData,
success: function(html) {
// alert(html);
$('#cast2').html(html);
}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以创建一个为 true 或 false 的变量,如果一旦将其设置为 false 且警报已被触发,用 if 来检查它是真是假。
You could make a variable which is either true or false, if the alert has been triggered once put it on false & check with an if, if its true or false.
您在这里使用字符串而不是串联:
您需要将 j 放在引号之外:
否则它始终是未定义的。
只是好奇,顺便问一下,为什么你需要在这里循环?
You're using a string instead of a concatenation here:
You need to place j outside of the quotes:
Otherwise it is always undefined.
Just curious, by the way, why do you need to loop here anyway?
绝对没有理由循环输入元素来确定是否检查其中任何一个。由于您已经在使用 :checked 选择器,只需检查匹配元素集的长度 - 这非常简单:
There is absolutely no reason what-so-ever to loop over input elements to determine if any of them are checked. Since you're already using the :checked selector, simply check the length of the matched set of elements - it's very simple:
试试这个
,如果您需要提醒一次 - 使用您的 j 计数器
try this
and if you will need to alert once - use yours j counter
据我所知,您也不想执行 else 语句,因此让 for 循环运行是没有用的。只需使用:
As far as I can tell, you don't want to do the else statement either, so there's no use of letting the for loop run. Simply use:
您是否尝试让它退出 for 循环到另一个函数,如果它等于未定义,则该函数会抛出错误,因为它看起来像您只是在尝试提交表单。因此,只要让它在未定义时退出到一个函数,该函数会抛出一个警报,说明你喜欢的任何内容。
did you try just having it exit the for loop to another function that throws an error if it equals undefined since it looks like your just trying to submit the form. So just make it exit on undefined to a function that throws an alert saying whatever you like.