GGsThePlayDude GGsThePlayDude - 2 months ago 7
HTML Question

javascript not resetting what is in the textbox when the button is submitted

I am new with this thing! I want the value of the textbox field to not be deleted even if the form is submitted

Here is my html page

<form action="" method="post">
<label>Firstname: </label><input type="text" name="fname" id="fname"/>
<label>Lastname: </label><input type="text" name="fname" id="fname"/>
<button type="submit">SUBMIT</button>
</form>


This is just a little sample

I want that if he already inputted a firstname and not inputted lastname, the inputted firstname will stay, while there will be an error in the lastname, how will I do that? because if I have a big form, specially a registration form, when i press the button and the client will got it wrong all what is inside the textbox will reset, instead of just remaining the correct things, it is not a very user-friendly thing right? thanks for helping me!

Answer
window.onload=function(){
a=function(b){
return document.getElementById(b);
};

var elems=[
//add all element ids here:
a("fname"),a("lastname")
];


elems.forEach(function(elem){
//restore
elem.value=localStorage.getItem(elem.id);

//add EventListener
elem.onchange=function(){
localStorage.setItem(this.id,this.value);
}
});
};

This stores the value to the localStorage when it is changed and writes it back into the field when the page is reloaded

Comments