There is an number input with min of ‘2’ and max of ’10’. By default this input is disabled. Nearby checkbox if checked toggles ‘disabled’ attribute so input become enabled and sets ‘2’ as a default value. When checkbox is not checked it resets the value of input so you can see a placeholder text insted of the number. The problem is how to restore the last entered value of input before its deactivation?
For example:
- Checkbox is active: input becomes enabled an sets ‘2’ as a default value.
- I change its value to ‘7’.
- I deactivate checkbox, so input becomes disabled and its value resets to ”.
- I activate checkbox again and wait for input to display early entered ‘7’, but see default ‘2’ instead.
Wrote the following code. I don’t know how to get rid of passQuantityInput.value = '2'
after I called it for the first time.
const Input = document.querySelector('#input');
const Checkbox = document.querySelector('#box');
let inputValue = Input.value;
Checkbox.addEventListener('click',function(){
if (this.checked){
Input.toggleAttribute('disabled');
Input.value = '2';
Input.value = getValue(); //this line returns "The specified value "NaN" cannot be parsed, or is out of range."
}
if (!this.checked){
Input.toggleAttribute('disabled');
Input.value = '';
}
})
Input.addEventListener('input',getValue);
function getValue(){
let inputValue = this.value;
if(this.value<2){
this.value = '';
} else if (this.value>10){
this.value = '10';
}
return inputValue;
}
4
Answers
Try changing your function getValue to this:
Change the Checkbox.addEventListener part to this
So the value is saved in inputValue before the shown value is set to ”.
To fix this issue you can define a variable outside of function or Event listener and the value will be 2.
suppose, we named the variable "defaultValue"
When you get the value from input, you can update the value of defaultValue and every time your event listener enabled set the value with defaultValue.
It maybe simpler to use a data attribute to store the current input value. That way you don’t have to rely on global variables.
Set a
current
attribute on the input element, and assign it an initial value. Any changes to the input value are stored on the data attribute, when the checkbox is toggled it retrieves thecurrent
value from the input element’s dataset / sets the value to an empty string.There is such a thing as HTMLInputElement.defaultValue that you can use here