0

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

1
  • you have tagged it with jquery, why do you use plain js? perhaps we need some more information about your html structure Commented Jan 18, 2017 at 6:48

2 Answers 2

1

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;  
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0
<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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.