TypeError: inputWidth.addEventListener is not a function : const inputWidth =…
- User
TypeError: inputWidth.addEventListener is not a function : const inputWidth = document.querySelectorAll('xxx'); const inputHeight = document.querySelectorAll('yyy');
if (inputWidth && inputHeight) { function validateInput(inputField) { let currentValue = parseInt(inputField.value);
const nearestDivisibleByEight = Math.round(currentValue / 8) * 8; inputField.value = nearestDivisibleByEight; }
inputWidth.addEventListener('input', function() { validateInput(inputWidth); });
inputHeight.addEventListener('input', function() { validateInput(inputHeight); }); }
- Assistant
The error message "TypeError: inputWidth.addEventListener is not a function" suggests that the variable
inputWidthdoes not have theaddEventListenermethod.The issue is most likely that
document.querySelectorAll('xxx')is returning a NodeList instead of a single element. ThequerySelectorAllmethod returns a list of all elements that match the given selector. To select a single element, you can usedocument.querySelector('xxx')instead.Here's the corrected code:
const inputWidth = document.querySelector('xxx'); const inputHeight = document.querySelector('yyy'); if (inputWidth && inputHeight) { function validateInput(inputField) { let currentValue = parseInt(inputField.value); const nearestDivisibleByEight = Math.round(currentValue / 8) * 8; inputField.value = nearestDivisibleByEight; } inputWidth.addEventListener('input', function() { validateInput(inputWidth); }); inputHeight.addEventListener('input', function() { validateInput(inputHeight); }); }Make sure to replace
'xxx'and'yyy'with the appropriate selectors to select the input elements you want to listen for input on. - User
I need to get an integer number returned from these inputWidth and inputHeight for JSON values. how?
- Assistant
To get an integer value from the
inputWidthandinputHeightelements, you can use theparseInt()function.Here's an updated version of the code that parses the input values as integers and returns them:
const inputWidth = document.querySelector('xxx'); const inputHeight = document.querySelector('yyy'); if (inputWidth && inputHeight) { function validateInput(inputField) { let currentValue = parseInt(inputField.value, 10); if (!isNaN(currentValue)) { const nearestDivisibleByEight = Math.round(currentValue / 8) * 8; inputField.value = nearestDivisibleByEight; return nearestDivisibleByEight; } return null; // Return null or any default value if the input is not a valid number } inputWidth.addEventListener('input', function() { const widthValue = validateInput(inputWidth); if (widthValue !== null) { // Use the widthValue for JSON values or any other purpose } }); inputHeight.addEventListener('input', function() { const heightValue = validateInput(inputHeight); if (heightValue !== null) { // Use the heightValue for JSON values or any other purpose } }); }