1

I have this HTML form:

<div class="input_fields_wrap">
    <div class="form-group row">
        <label class="col-sm-3 col-form-label">Items</label>
        <div class="col-sm-7">
            <input type="text" name="items[]" class="form-control items" id="items">
        </div>
        <div class="col-sm-2">
            <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>   
        </div>                      
    </div>
</div>

It has Add+ functionality which basically add more field. So If I add more field I have multiple ID of this field like: items, items1, items2, etc..

Now, In my JavaScript validation function, I want to check if this Items field or fields are empty or not.

I can check one field but how can I check multiple fields using JavaScript?

JavaScript validation code for one items field:

var items           =   document.getElementById("items");
if (items.value == "") { 
    alert("Item name is reuired"); 
    items.focus(); 
    return false; 
}

JavaScript code for Add+ functionality:

var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();     
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        var form = '<div class="delete-row"><div class="form-group row"><label class="col-sm-3 col-form-label">Items</label><div class="col-sm-7"><input type="text" name="items[]" class="form-control items"></div><div class="col-sm-2"><a href="#" class="remove_field btn btn-danger btn-sm">( X )</a></div></div></div>';
        $(wrapper).append('<div>'+form+'</div>'); //add input box
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); 
    $(this).parents('.delete-row').remove(); x--;
})    

Full Validation code:

function validateForm () {

    var amount          =   document.forms["salesform"]["amount"];               
    var buyer           =   document.forms["salesform"]["buyer"];    
    var buyerRegex      =   /^[a-zA-Z0-9_ ]*$/;     
    var receipt_id      =   document.forms["salesform"]["receipt_id"];  
    var receiptIdRegex  =   /^[a-zA-Z_ ]*$/;        
    var items           =   document.querySelectorAll(".items");
    var itemsRegex      =   /^[a-zA-Z_ ]*$/;
    var buyer_email     =   document.forms["salesform"]["buyer_email"];  
    var note            =   document.forms["salesform"]["note"];  
    var city            =   document.forms["salesform"]["city"];  
    var phone           =   document.forms["salesform"]["phone"];
    var entry_by        =   document.forms["salesform"]["entry_by"];        


    if (amount.value == "") { 
        alert("Please enter the amount."); 
        amount.focus(); 
        return false; 
    } else if (isNaN(amount.value)) {
        alert("Amount should be only numeric value."); 
        amount.focus(); 
        return false; 
    }

    if (buyer.value == "") { 
        alert("Buyer name is required"); 
        buyer.focus(); 
        return false; 
    } else if (!buyerRegex.test(buyer.value)) {
        alert("Buyer name only contain letter, number and space."); 
        buyer.focus(); 
        return false; 
    } else if (buyer.value.length > 20 ) {
        alert("Buyer name must be less than 20 characters long."); 
        buyer.focus(); 
        return false; 
    }

    if (receipt_id.value == "") { 
        alert("Receipt Id is reuired"); 
        receipt_id.focus(); 
        return false; 
    } else if (!receiptIdRegex.test(receipt_id.value)) {
        alert("Receipt Id must contain only characters."); 
        receipt_id.focus(); 
        return false; 
    }

    items.forEach(ele => {  
        if (ele.value == "") {
            alert("Item name is required");
            ele.focus();// focuses on that particular input
            return false;
        }
    })

    return true;
}
Shibbir
  • 1,963
  • 2
  • 25
  • 48
  • 2
    `id` should be unique - use a `class` instead (`document.querySelectorAll('.form-control')`) or else just add a `required` attribute to the textfields. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#The_required_attribute – Lain Jun 19 '19 at 12:31
  • the id is already showing unique like items, items1, items2, etc. – Shibbir Jun 19 '19 at 12:32
  • What the person above is suggesting is that each of your inputs have the same class and you query for that class instead of by id. – Bash Jun 19 '19 at 12:34
  • just use [required] and omit the javascript. like someone above suggested – Ruedi.Angehrn Jun 19 '19 at 12:39
  • You don't have class items for your text field – Shubham Dixit Jun 19 '19 at 12:50
  • Just as a not.. do not update your question after half a day to ask about a totally different issue. It invalidates all answers provided up to that point. – Lain Jun 19 '19 at 14:23

4 Answers4

3

You can try something like this,Query SelectorAll,As forEach returns undefined ,you can try with every

const items = [...document.querySelectorAll("input[type=text]")];
items.every(ele => {
  //console.log(ele.value)
  if (ele.value == "") {
    alert("Item name is reuired");
    ele.focus();// focuses on that particular input
    return false; 
}
})
<div class="input_fields_wrap">
  <div class="form-group row">
    <label class="col-sm-3 col-form-label">Items</label>
    <div class="col-sm-7">
      <input type="text" name="items[]" class="form-control" id="items">
    </div>
    <div class="col-sm-2">
      <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
    </div>
  </div>
</div>
Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46
1

Here's a version of Shubh's answer but querying by class. It's very important to note that you cannot short circuit forEach in javascript by returning from the function, so I altered this solution to use a for loop. For more information you can read this SO question about it.

let items = document.querySelectorAll(".items")
for (let i = 0; i < items.length; i++) {
  if (items[i].value == "") {
    alert("Item name is required");
    items[i].focus(); // focuses on that particular input
    return false;
  }
})
<div class="input_fields_wrap">
  <div class="form-group row">
    <label class="col-sm-3 col-form-label">Items</label>
    <div class="col-sm-7">
      <input class="items" type="text" name="items[]" class="form-control">
    </div>
    <div class="col-sm-2">
      <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
    </div>
  </div>
</div>
Bash
  • 628
  • 6
  • 19
  • ncaught SyntaxError: Identifier 'items' has already been declared – Shibbir Jun 19 '19 at 12:38
  • If you already have a variable called items, you will need to call the items in the code snippet by a different name. – Bash Jun 19 '19 at 12:42
  • can you tell me why it's reloading the page after showing the alert message? – Shibbir Jun 19 '19 at 13:11
  • Wow, finally we save me :) Thanks a lot. You should post that URL here to see everyone what was the problem to the foreach/ – Shibbir Jun 19 '19 at 13:58
0

I would change the input field to have a class that's called item

Then I would loop all those items.

var items = document.querySelectorAll('.item');
for (var i = 0; i < items.length; i++) { 
    var item = items[i];
    // validate
}
Oliver Nybo
  • 560
  • 1
  • 6
  • 24
0

The functionality to increment the id is quite useless in your case. getElementById will give you the first match. In your case, where you want to check several elements it'll be wise to use QuerySelectorAll:

document.querySelectorAll('.form-control').forEach(node => {
    if(items.value == "") {
        ...
    }
})
Smytt
  • 364
  • 1
  • 11