Ducaz035
Ducaz035

Reputation: 3132

Keeping submit button disabled until dynamically created required fields are filled

I want to keep the submit button disabled until the required fields are being filled.

Firstly , I found some questions about this issue but the problem was i have some required fields and not required fields also i am creating these fields dynamically. Here is an example:

<input type="text" id="releaseartist" name="releaseartist" required="true" placeholder="Required Field"/>

Also i have input like that , this is how i am creating them dynamically,

var trackartistinput = document.createElement('input');
trackartistinput.setAttribute('type', "text");
trackartistinput.setAttribute('id', "trackartist" + i);
trackartistinput.setAttribute('name', "trackartist");
trackartistinput.setAttribute("required", true);
trackartistinput.setAttribute("placeholder", "Required Field");
trackartistinput.setAttribute("class", "required");

And this is my submit button :

<input type="submit" class="btn btn-primary" value="Submit" id="form-submit" onclick="return myConfirm();" />

Upvotes: 2

Views: 2460

Answers (2)

Hemant Metalia
Hemant Metalia

Reputation: 30648

you can check the count of required fields added in the document so far and based on the counts you can set the property of submit button to disabled or enabled.

you can count required class components as follow:

var numItems = $('.required').length

EDIT

to check if all the required class elements are filled you can check as follow:

var required_ele = document.getElementsByClassName('required');
var allfilled=true;
for (var i = 0; i < required_ele.length; ++i) {
    var item = required_ele[i];  
    if(item.value.length==0){
      allfilled=false;
    }
}
if(allfilled){
   document.getElementById("form-submit").disabled = false;
}
else{
  document.getElementById("form-submit").disabled = true;
}

Upvotes: 2

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

  • Start with button having disabled attribute set.
  • Add change event listener to form element (assuming that is the parent of all input elements)
  • in change handler check if all required fields are filled, if yes, enable submit button

This work well even if user remove value entered in required field later, submit button will become disabled again

Upvotes: 2

Related Questions