Skip to main content
Code Review

Return to Answer

Commonmark migration
Source Link

#EDIT#

EDIT

#Original#

Original

#EDIT#

#Original#

EDIT

Original

Post Migrated Here from stackoverflow.com (revisions)
Source Link
Jhecht
  • 111
  • 2

#EDIT#

Changed the event on the form elements to be the input event instead of keypress event

#Original#

You'll have to forgive any bugs -- I'm on cold medicine right now due to an unfortunate malady.

That being said, I'd like to explain [].slice.call(document.querySelectorAll('<selector here>') : this is a way to turn the result from .querySelectorAll() from a NodeList to an Array so that I could use any/all of the methods available to array objects. In this case, I used .forEach.

that being said, the code here just adds some events to the inputs using javascript, and will only check the parent form that the event is triggered (this way you don't have to loop through all the elements in the DOM every time someone changes a field value)

Quick Edit Rajesh just posted an answer, and I feel like his is much simpler, but I spent the time to write this answer out so I'm going to post it anyway.

window.addEventListener('load', function(e){
 var forms = document.querySelectorAll('form');
 //get the forms
 [].slice.call(document.querySelectorAll('input.optional')).forEach(function(optional){
 optional.style.display='none';
 });
 //Hide all optional fields on load really quick
 for(let i = 0, form; form = forms[i]; i++){
 form.querySelector('[type="submit"]').setAttribute('disabled','disabled');
 //Since we are firing onload, let's get any submit buttons to be disabled.
 [].slice.call(form.querySelectorAll('textarea, input[type="email"]'))
 .forEach(function(field){
 field.addEventListener('input', function(e){
 if([].slice.call(this.form.querySelectorAll('textarea, input[type="email"]:not(.optional)')).every(function(input){ return input.value.length > 0; })){
 //if every field that is not optional has a length > 0, continue
 
 this.form.querySelector('[type="submit"]').removeAttribute('disabled');
 //Remove the disabled attribute from the submit button
 [].slice.call(this.form.querySelectorAll('.optional')).forEach(function(optional){
 optional.style.display='';
 });
 //Show all optional fields
 
 }
 });
 });
 }
 
 
});
<form>
 <textarea></textarea>
 <input type="email">
 <button type="submit">Submit</button>
</form>
<form>
 <textarea></textarea>
 <input class="optional" type="email">
 <button type="submit">Submit</button>
</form>
<form>
 <textarea></textarea>
 <input type="email">
 <button type="submit">Submit</button>
</form>

default

AltStyle によって変換されたページ (->オリジナル) /