How do I keep the previous input status with a `change` event?
I have two radio button inputs and when one of them is clicked it will be checked and will alert the user if he or she will send data. Any of these can be pre-checked depending on the user's log history.
The problem is this: I want to revert the checked state of the radio inputs when the user clicks the cancel button of the alert dialog.
This would be easy to implement if the event change
passes the pre-change status and post-change status, but it doesn't seem to be the case.
Is there a way to record the previous status of the inputs to change
them?
source to share
You can save the link to RadioNodeList
radio stations and also save the current value.
When the event listener starts change
, you can update the saved value or discard the change by assigning the old value as a property value
.
This will work if all radios have different meanings.
var form = document.forms[0],
els = form.elements.myradio,
val = els.value;
form.addEventListener('change', function(e) {
if(confirm('Do you want to change?'))
val = els.value; // Update the value
else
els.value = val; // Undo (assign the old value)
});
<form>
<label><input type="radio" name="myradio" value="1" checked />1</label>
<label><input type="radio" name="myradio" value="2" />2</label>
<label><input type="radio" name="myradio" value="3" />3</label>
</form>
source to share