Search code examples
javascripthtmlfor-looplimitdom-manipulation

JavaScript Restrict the amount of form inputs added onto the DOM


I have a button that places a user's forms inputs onto the DOM, as well as removing them. The issue is that I'm trying to create a limited amount of inputs that are allowed to be added onto the DOM. Once two inputs are placed onto the DOM I would like the disabledbtn button to disable.

The code which I have used is:

// Restrict Amount Of Inputs On Dom 
   let count;
   for (count = 0; count < 2; count++) {
    disabledbtn.disabled = true;
   };


//I've also attempted an IF Statement:
   // Restrict Amount Of Inputs On Dom 
   let count = 0;
   count += 1;
   if (count.length >= 2) {
    disabledbtn.disabled = true;
   };

And here is a full code snippet:

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });
  
// Delete From The Dom.
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
  e.preventDefault();
  // Remove Form Input.
  let h6_e = document.querySelectorAll('.h6_exercise_class');
   // Empty String.
  if (!h6_e.length) {
    return false;
  } else {
    h6_e[h6_e.length - 1].remove();
  };
});

// Add User's Input To The Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledbtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value.
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Empty String.
  if (value ===  "" || value == null) {
    return false;
  };

  // Create Elements
  const h6_exercise = document.createElement('h5');

  // Add Content
  h6_exercise.textContent = value;

  // Adding Class
  h6_exercise.classList.add('h6_exercise_class');

  // Restrict Number Of Chacracters 
  if(value.length > 15){
    return false;
    };

  // Append To Dom 
  addExerciseDom.appendChild(h6_exercise); 

});
/*------------------ Modals & forms--------------------*/
      .modal{
        border: 0.3rem solid black;
        overflow-y: visible;
      }

      .modal-position{
        margin-top: 50%;
      }
      
      .modal .modal-footer{
        text-align: center;
      }

      label{
          color: #000 !important;  
      }
    
      /* Remove Btn */
      .remove-padding{
        margin-top: 1.5rem !important;
        margin-bottom: 1.5rem !important;
      }
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title></title>

  <!-- Google icons -->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <!-- Sytle.css -->
  <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>

  <!----- user's input ------->
  <div class="row">
    <div class="col s12 center valign-wrapper center-align">
      <div class=" exercise-dom delete">
        <!--Users text input h6---->
      </div>
    </div>
  </div>

  <!-- Btn/Modals/form -->
  <div class="row">
    <!-- Dom Btn -->
    <div class="col s12 center ">
      <a href="#exercise" class="disabled-exersicebtn btn-floating btn-small darken-4 z-depth-2 black center modal-trigger ">
        <i class="material-icons white-text">add </i>
      </a>
    </div>
  </div>
  <!-- Modal/form -->
  <div class="modal modal-position" id="exercise">
    <div class="modal-content">
      <div class="row exercises-padding">
        <form class="col s12 exercises-form" autocomplete="off">
          <div class="input-field col s10">
            <i class="material-icons prefix">fitness_center</i>
            <input type="text" id="autocomplete-input" class="autocomplete center">
            <label for="autocomplete-input">
              <h6>Input</h6>
            </label>
          </div>
          <div class="modal-footer">
            <input class="modal-close btn black" type="submit" value="Submit">
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Remove Users Btn -->
  <div class="col s12 center remove-padding">
    <a href="#" class="del-exercise-btn btn-floating btn-small darken-4 z-depth-2 black center modal-trigger">
      <i class="material-icons white-text ">remove </i>
    </a>
  </div>

  <!-- Compiled and minified JavaScript -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

  <!-- app.JavaScript -->
  <script src="app.js"></script>
</body>

</html>


Solution

  • First of all you have anchor tag, which don't have disabled property.

    So what you can do is create a function, which will check for added exercise, and disable/enable button.

    Note again here disabling by CSS

    What I did create a function which will be called on adding and removing exercise.

    This function will add/remove class disabled-anchor if there is 2 or more exercises

    function checkForDisabled() {
       if (document.querySelectorAll('.h6_exercise_class').length >= 2) {
      disabledbtn.classList.add('disabled-anchor');
      } else {
        disabledbtn.classList.remove('disabled-anchor');
      }
    }
    

    And below CSS

    .disabled-anchor {
        pointer-events: none;
        opacity: 0.5;
    }
    

    // ----------------Models Materialize Framework----------------
    document.addEventListener('DOMContentLoaded', () => {
        var elems = document.querySelectorAll('.modal');
        var instances = M.Modal.init(elems);
      });
      
    // Delete From The Dom.
    const delExerciseBtn = document.querySelector('.del-exercise-btn');
    
    delExerciseBtn.addEventListener('click', (e) => {
      e.preventDefault();
      // Remove Form Input.
      let h6_e = document.querySelectorAll('.h6_exercise_class');
       // Empty String.
      if (!h6_e.length) {
        return false;
      } else {
        h6_e[h6_e.length - 1].remove();
      };
      checkForDisabled();
    });
    
    // Add User's Input To The Dom.
    const addExerciseDom = document.querySelector('.exercise-dom');
    const exerciseForm = document.querySelector('.exercises-form');
    const disabledbtn = document.querySelector('.disabled-exersicebtn');
    
    exerciseForm.addEventListener('submit', (e) => {
    e.preventDefault();
    
      // Get Input Value.
      const value = exerciseForm.querySelector('input[type="text"]').value;
    
      // Empty String.
      if (value ===  "" || value == null) {
        return false;
      };
    
      // Create Elements
      const h6_exercise = document.createElement('h5');
    
      // Add Content
      h6_exercise.textContent = value;
    
      // Adding Class
      h6_exercise.classList.add('h6_exercise_class');
    
      // Restrict Number Of Chacracters 
      if(value.length > 15){
        return false;
        };
    
      // Append To Dom 
      addExerciseDom.appendChild(h6_exercise);
      checkForDisabled();
     
    
    });
    
    function checkForDisabled() {
       if (document.querySelectorAll('.h6_exercise_class').length >= 2) {
      disabledbtn.classList.add('disabled-anchor');
      } else {
        disabledbtn.classList.remove('disabled-anchor');
      }
    }
    /*------------------ Modals & forms--------------------*/
          .modal{
            border: 0.3rem solid black;
            overflow-y: visible;
          }
    
          .modal-position{
            margin-top: 50%;
          }
          
          .modal .modal-footer{
            text-align: center;
          }
    
          label{
              color: #000 !important;  
          }
        
          /* Remove Btn */
          .remove-padding{
            margin-top: 1.5rem !important;
            margin-bottom: 1.5rem !important;
          }
          
          .disabled-anchor {
            pointer-events: none;
            opacity: 0.5;
          }
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
      <title></title>
    
      <!-- Google icons -->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    
      <!-- Compiled and minified CSS -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    
      <!-- Sytle.css -->
      <link rel="stylesheet" type="text/css" href="style.css">
    
    </head>
    <body>
    
      <!----- user's input ------->
      <div class="row">
        <div class="col s12 center valign-wrapper center-align">
          <div class=" exercise-dom delete">
            <!--Users text input h6---->
          </div>
        </div>
      </div>
    
      <!-- Btn/Modals/form -->
      <div class="row">
        <!-- Dom Btn -->
        <div class="col s12 center ">
          <a href="#exercise" class="disabled-exersicebtn btn-floating btn-small darken-4 z-depth-2 black center modal-trigger ">
            <i class="material-icons white-text">add </i>
          </a>
        </div>
      </div>
      <!-- Modal/form -->
      <div class="modal modal-position" id="exercise">
        <div class="modal-content">
          <div class="row exercises-padding">
            <form class="col s12 exercises-form" autocomplete="off">
              <div class="input-field col s10">
                <i class="material-icons prefix">fitness_center</i>
                <input type="text" id="autocomplete-input" class="autocomplete center">
                <label for="autocomplete-input">
                  <h6>Input</h6>
                </label>
              </div>
              <div class="modal-footer">
                <input class="modal-close btn black" type="submit" value="Submit">
              </div>
            </form>
          </div>
        </div>
      </div>
    
      <!-- Remove Users Btn -->
      <div class="col s12 center remove-padding">
        <a href="#" class="del-exercise-btn btn-floating btn-small darken-4 z-depth-2 black center modal-trigger">
          <i class="material-icons white-text ">remove </i>
        </a>
      </div>
    
      <!-- Compiled and minified JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    
      <!-- app.JavaScript -->
      <script src="app.js"></script>
    </body>
    
    </html>