not_in
not_in

Reputation: 1

Disable input in a form when another input is filled in JS

I am trying to disable all input type in a form when one of them is checked or filled with a value.

When one of the checkbox is checked will disable the other two fields, same for the input text.

Here some code try:

HTML

<form action="">
   <input type="text" id="name"/>
   <input type="checkbox" id="days" name="days" />
   <input type="checkbox" id="months" name="months" />
</form>

JS

 function disableInput(e) {
    if(e.target.value !== 0) {
       document.getElementById("days").disabled = true;
       document.getElementById("months").disabled = true;
     }else {
       document.getElementById("days").disabled = false;
       document.getElementById("months").disabled = false;
            }
        }

const name = document.querySelector('#name');
name.addEventListener('input', disableInput);

How can I manage this in vanilla JS?

Upvotes: 0

Views: 1841

Answers (5)

Lakhveer_ 007
Lakhveer_ 007

Reputation: 1

document.addEventListener("DOMContentLoaded", function() {
      const input1 = document.getElementById('input1');
      const input2 = document.getElementById('input2');

      input1.addEventListener('input', () => {
        if (input1.value !== '') {
          input2.disabled = true;
        } else {
          input2.disabled = false;
        }
      });
    });
 <form>
    <label for="input1">Input 1:</label>
    <input type="text" id="input1"><br><br>
    
    <label for="input2">Input 2:</label>
    <input type="text" id="input2">
  </form>

Upvotes: 0

Lakhveer_ 007
Lakhveer_ 007

Reputation: 1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>`enter code here`
<style>
    .error{
        color: red;
    }
</style>
<body>

<form id="registrationForm" autocomplete="off">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" onblur="disableField(this)" oninput="checkSubmitButton()">
    <button type="button" onclick="toggleInput('name')">edit</button>
    <span class="error" id="nameError"></span>
    <br><br>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" onblur="disableField(this)" oninput="checkSubmitButton()">
    <button type="button" onclick="toggleInput('email')">edit</button>
    <span class="error" id="emailError"></span>
    <br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" onblur="disableField(this)" oninput="checkSubmitButton()">
    <button type="button" onclick="toggleInput('password')">edit</button>
    <span class="error" id="passwordError"></span>
    <br><br>

    <label for="confirmPassword">Confirm Password:</label>
    <input type="password" id="confirmPassword" name="confirmPassword" onblur="disableField(this)" oninput="checkSubmitButton()">
    <button type="button" onclick="toggleInput('confirmPassword')">edit</button>
    <span class="error" id="confirmPasswordError"></span>
    <br><br>

    <input type="submit" id="submitButton" disabled></input>
</form>

<script>
const form = document.getElementById("registrationForm");
function disableField(inputField) {
    if (inputField.value.trim() !== '') {
        inputField.disabled = true;
    }
}

function toggleInput(inputId) {
    const inputField = document.getElementById(inputId);
    inputField.disabled = !inputField.disabled;
    checkSubmitButton();
}

function checkSubmitButton() {
    const name = document.getElementById("name").value.trim();
    const email = document.getElementById("email").value.trim();
    const password = document.getElementById("password").value.trim();
    const confirmPassword = document.getElementById("confirmPassword").value.trim();
    const submitButton = document.getElementById("submitButton");
    const nameError = document.getElementById("nameError");
    const emailError = document.getElementById("emailError");
    const passwordError = document.getElementById("passwordError");
    const confirmPasswordError = document.getElementById("confirmPasswordError");
    const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    nameError.textContent = "";
    emailError.textContent = "";
    passwordError.textContent = "";
    confirmPasswordError.textContent = "";

    let isValid = true;

    if (name === "") {
        nameError.textContent = "Name is required";
        isValid = false;
    }

    if (email === "") {
        emailError.textContent = "Email is required";
        isValid = false;
    } else if (!emailPattern.test(email)) {
        emailError.textContent = "Invalid email format";
        isValid = false;
    }

    if (password === "") {
        passwordError.textContent = "Password is required";
        isValid = false;
    } else if (password.length < 6) {
        passwordError.textContent = "Password must be at least 6 characters long";
        isValid = false;
    }

    if (confirmPassword === "") {
        confirmPasswordError.textContent = "Please confirm your password";
        isValid = false;
    } else if (confirmPassword !== password) {
        confirmPasswordError.textContent = "Passwords do not match";
        isValid = false;
    }

    if (isValid) {
        submitButton.disabled = false;
    } else {
        submitButton.disabled = true;
    }



form.addEventListener("submit", function (event) {
            // event();
            if (isValid) {
                // Retrieve existing user data from local storage or initialize an empty array
                const userData = JSON.parse(localStorage.getItem('userData')) || [];
                // console.log(userData);

                // Add the new user data
                userData.push({ name, email, password });
                
                // Save the updated user data back to local storage
                localStorage.setItem('userData', JSON.stringify(userData));

                // console.log(userData);
                form.reset(); // Clear the form after submission
                // alert('Form Succesfully Submitted');
                // window.location.href="/preet/tictacgame.html"
            }
        
});
}
</script>

</body>
</html>

Upvotes: 0

EzioMercer
EzioMercer

Reputation: 2005

This is my simple solution:

const allInputs = document.querySelectorAll('.radio-input');

allInputs.forEach((input) => {
  input.addEventListener('input', (e) => {
  
    let value;
    
    switch(e.target.type) {
      case 'checkbox':
        value = e.target.checked;
        break;
      case 'text':
        value = e.target.value;
        break;
    }
    
    const needDisable = !(value === '' || value === false);
    
    allInputs.forEach((input) => {
      if (input === e.target) {
        input.disabled = false;
        return;
      }
      
      input.disabled = needDisable;
    })
  });
});
<form action="">
   <input type="text" class="radio-input" id="name"/>
   <input type="checkbox" class="radio-input" id="days" name="days" />
   <input type="checkbox" class="radio-input" id="months" name="months" />
</form>

Upvotes: 0

Aurange
Aurange

Reputation: 963

function lockOut(e) {
  this.querySelectorAll("input:not(#" + e.srcElement.id + ")").forEach(function(elem) {
    if (e.srcElement.type !== "text") elem.disabled = !elem.disabled;
    else if (e.srcElement.value.length > 0) elem.disabled = true;
    else elem.disabled = false;
  });
}

document.querySelector("form").addEventListener("input", lockOut);
<form action="">
  <input type="text" id="name" />
  <input type="checkbox" id="days" name="days" />
  <input type="checkbox" id="months" name="months" />
</form>

Upvotes: 0

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20924

The input event will bubble up. So listen for that event on the <form> element to capture all activity on the inputs.

When the event is triggered, check the type of event and if either the value is empty or the checked property equals true, depending on the type value.

Then loop over all the inputs in the form. All your inputs can be found in the elements property on the form. In the loop disable all the inputs except the one you're currently using.

Restore all the inputs when the aforementioned condition is not met.

const form = document.querySelector('form');

function disableInputs(exception) {
  for (const input of form.elements) {
    if (input !== exception) {
      input.disabled = true;
    }
  }
}

function enableInputs() {
  for (const input of form.elements) {
    input.disabled = false;
  }
}

form.addEventListener('input', event => {
  const { target } = event;

  if (
    (target.type === 'text' && target.value !== '') ||
    (target.type === 'checkbox' && target.checked === true)
  ) {
    disableInputs(target);
  } else {
    enableInputs();
  }
});
<form action="">
  <input type="text" id="name" />
  <input type="checkbox" id="days" name="days" />
  <input type="checkbox" id="months" name="months" />
</form>

Upvotes: 1

Related Questions