How to alert once in a JavaScript loop
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开发者_如何学C 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);
}
});
}
}
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.
if (showAlert==true)
{
alert ("Please select atleast one product");
showAlert = false;
}
You're using a string instead of a concatenation here:
$("input[name=select+j]:checked").val();
You need to place j outside of the quotes:
$("input[name=select"+j+"]:checked").val();
Otherwise it is always undefined.
Just curious, by the way, why do you need to loop here anyway?
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:
var $checked = $("input[type='checkbox']:checked");
// If none of the checkboxes are checked, alert to the user
if ( !$checked.length ) {
alert("Please select atleast one product");
} else {
// do ajax post stuff here.
}
try this
if(typeof(select)=='undefined')
and if you will need to alert once - use yours j counter
if (j==1) {alert('')}
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:
if(select==undefined)
{
alert ("Please select atleast one product");
j = numOflimit+1;
}
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.
精彩评论