Problem:
I would to enable a button if the value inside the textbox is equal to ‘mypassword’. if the value inside the textbox is not equal to ‘mypassword’ I would like to disabale this button. I have tried the code below but it is not working for some reason.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery-3.5.0.min.js"></script>
<script>
const buttonElement = document.querySelector('submit')
const inputElement = document.querySelector('password')
inputElement.addEventListener('change'), (e) => {
if (e.target.value.includes('mypassword')) {
buttonElement.disabled = false
} else {
buttonElement.disabled = true
}
}
</script>
</head>
<body>
<form action="review.php">
<label for="">Password: </label><input type="password" name="password" id="password" class="password">
<button type="submit" id='submit' class='submit'>Review Report</button>
</form>
</body>
</html>
Solution:
You have a syntax error in your addEventListener
call. The callback function isn’t inside the addEventListener
call. Also I believe you want to listen to keyup events not change events.
const buttonElement = document.querySelector('#submit')
const inputElement = document.querySelector('#password')
inputElement.addEventListener('keyup', (e) => {
if ( e.target.value.includes('mypassword')) {
buttonElement.disabled = false
} else {
buttonElement.disabled = true
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="jquery-3.5.0.min.js"></script>
</head>
<body>
<form action="review.php">
<label for="">Password: </label><input type="password" name="password" id="password" class="password">
<button type="submit" id='submit' class='submit' disabled>Review Report</button>
</form>
</body>
</html>
Also, you can simplify your event handler to this if you want to.
const buttonElement = document.querySelector('#submit')
const inputElement = document.querySelector('#password')
inputElement.addEventListener('keyup', (e) => {
buttonElement.toggleAttribute('disabled', !(e.target.value.includes('mypassword')));
})