Reputation: 1146
I am developing a form with add more button. When I click the button, a set of field will be generated. I have done the javascript validation for this, if all the added field is empty alert the message. The code for that is:
var n = document.getElementById('cnnumrows').value, i;
if ( frm_add_announcement.sublink[1].checked == true ) {
for(i=1; i<=n; i++) {
if ( (document.getElementById('url'+i).value.trim()=="") && ( document.getElementById("document"+i).files.length == 0 ) ) {
alert("Enter a url/upload a file");
document.getElementById('captionurl').focus();
return false;
}
}
}
I have to change this to if any of the fields is inserted value no need to alert and if all is empty alert. Any suggestion
Upvotes: 0
Views: 470
Reputation: 1265
<script type="text/javascript">
document.form1.studentName.focus();
function validateform(){
var sname=document.form1.studentName.value;
var sclass=document.form1.studentClass.value;
var semail=document.form1.studentemail.value;
var sphone=document.form1.studentphone.value;
var flag=false;
var phoneno = /^\d{7}$/;
if(sname==null || sname==""){
alert("student name is empty\nFormate: XXXXXXXXX");
flag=false;
return false;
}else {
flag=true;
}
if(sclass==null || sclass==""){
alert("student class is empty\nFormate: XXXxx");
flag=false;
return false;
}else {
flag=true;
}
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(semail)) {
flag=true;
}else{
alert("student e-mail formate error \nFormate: [email protected]\n [email protected]");
flag=false;
return false;
}
if(sphone.match(phoneno)){
flag=true;
}else{
alert("student phone must contain atleast 7 digits\nFormate: XXXXXXX");
flag=false;
return false;
}
return flag;
};
</script>
Upvotes: 0
Reputation: 15442
try this:
var n = document.getElementById('cnnumrows').value;
if ((frm_add_announcement.sublink[1].checked)) {
// will be set to true if some value is inserted
var someValue = false;
for (var i = 1; i <= n; i++) {
if (document.getElementById('url' + i).value || document.getElementById("document" + i).files.length) {
someValue = true;
}
}
// if at this point someValue is still falsy - no values inserted, fire your alert
if (!someValue) {
alert("Enter a url/upload a file");
document.getElementById('captionurl').focus();
return false;
}
}
Upvotes: 1