I'm trying to make website which will enable button when the certain condition is met. But when I run it within simple if the condiiton is checked only at the beginning and it doesn't enable and disable on changing condition. Condition is changing inside other event listener so the condition is dynamically. The condition is met when the dicitonary consists only of true which means that input is proper
`var submitButton = document.getElementById("submit_button");`
And after some event listeners connected to inputs
`if(Object.values(check_dict).filter(x=>x==true).length === 6)
{
submitButton.disabled = false;
}
else
{
submitButton.disabled = true ;
}`
CodePudding user response:
pretty straight forward. add an eventlistener to the input you want to watch and then disable the submit button inside the function
document.getElementById('test').addEventListener('input',myFunc)
function myFunc(){
if(event.target.value == "x")document.getElementById("submit_button").disabled = true;
else document.getElementById("submit_button").disabled = false;
}
<input id ='submit_button' type='submit'>
<input id='test'>
CodePudding user response:
You could use removeAttribute()
and setAttribute()
to toggle the state of the submit button using a conditional.
See the snippit for a very simple example of how to toggle states using classes with .classList
along with add/remove attribute method.
const checkInput = (e) => {
if(e.target.value.length >= args.rules.length){
e.target.classList.remove('error')
e.target.classList.add('success')
submitBtn.removeAttribute('disabled')
inputDisplay.textContent = args.success.value
}else{
e.target.classList.add('error')
e.target.classList.remove('success')
submitBtn.setAttribute('disabled', 'true')
inputDisplay.textContent = args.error.value
}
}
const args = {
rules: {
length: 8
},
success: {
value: "Success! You may submit now!"
},
error: {
value: "Input must contain 8 or more characters!"
}
}
const fname = document.getElementById('fname')
const submitBtn = document.getElementById('submit')
const inputDisplay = document.getElementById('input-display')
inputDisplay.textContent = args.error.value
submitBtn.disabled = 'true'
fname.addEventListener('input', checkInput)
.success {
color: darkgreen;
background-color: lightgreen;
}
.error {
color: darkred;
background-color: pink;
}
<input name="firstname" id="fname" placeholder="Please enter your first name">
<button id="submit" type="button">Submit</button>
<div id="input-display"></div>