简体   繁体   中英

localStorage page does not display after submitting form

I'm having a problem where whenever I click the submit button, it refresh the page, the data is fine in localStorage though.

It is not a problem if internet is available because it will reload the page.

But it is annoying when I have no internet connection as it displays "No Internet connection" instead of displaying the page.

How can I make it update the div without a page refresh? Or let it refresh without letting me know I do not have an Internet connection.

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Local Storage</title> </head> <body> <div id="mydiv">Local Storage is </div> <div id="myCount">Item in Local Storage is </div> <br/> <div id="myResult">Result: </div> <br/> <form id="localStorageTest" method="post" action="" autocomplete="off"> <label>Name:</label> <input type="text" name="name" id="name" class="stored" value=""> <br/> <label>Message:</label> <textarea name="message" id="message" class="stored"></textarea> <br/> <input type="submit" class="demo-button" value="Submit" onclick="submitData();"> </form> <br/> <input type="submit" class="btn-clear" value="Clear Local Storage" onclick="clearStorage();"> <script> function lsTest() { var i = 'test'; try { localStorage.setItem(i, i); localStorage.removeItem(i); return true; } catch (e) { return false; } } if (lsTest() === true) { var retrievedObject = localStorage.getItem('testObject'); document.getElementById('mydiv').innerHTML += 'available.'; document.getElementById('myCount').innerHTML += localStorage.length; document.getElementById('myResult').innerHTML += retrievedObject; console.log('retrievedObject: ', JSON.parse(retrievedObject)); } else { document.getElementById('mydiv').innerHTML += 'unavailable.'; } function submitData() { var v_name = document.getElementById('name').value; var v_message = document.getElementById('message').value; var testObject = { 'name': v_name, 'message': v_message }; localStorage.setItem('testObject', JSON.stringify(testObject)); //localStorage.setItem('message', v_message); alert('Data: ' + localStorage.getItem('testObject')); } function clearStorage() { localStorage.clear(); location.reload(); } </script> </body> </html> 

Change submitData() and clearStorage() to:

function submitData(event){
    event.preventDefault();
    ...
}

function clearStorage(event){
    event.preventDefault();
    ...
}

That should fix your problem.

The problem is you're sending a form, which is basically just like clicking a link (the only difference here is that you're using an HTTP POST request, not a GET request, like clicking a link would).
Your form is:

  <form id="localStorageTest" method="post" action="" autocomplete="off">

The action attribute states the resource that is requested, and since it's blank, the page will essentially reload.

To prevent this, you need to intercept the form submission. The simplest way to do that is to remove the <form> element entirely; you don't need it anyway.

With a <form> in place, you can either intercept the click on the button or the form's submission by calling .preventDefault() on the click / submission event.

function submitData(e) {
    e.preventDefault(); // don't handle click the usual way after this function
    var v_name = document.getElementById('name').value;
    ...
}

This will update the div without page refresh

Copy the code to a file and run. Run code snippet might not support local storage

Changes

  • Fixed data population area
  • Added data population code in to a function populateData()
  • Stopped reloading the page and called populateData() when clearing the local storage
  • Changed input type in to button for "Clear Local Storage"

Use https://www.diffchecker.com/diff to find more changes

 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Local Storage</title> </head> <body> <div> Local Storage is <span id="myspan"></span> </div> <div> Item in Local Storage is <span id="myCount"></span> </div> <br/> <div> Result: <span id="myResult"></span> </div> <br/> <form id="localStorageTest" method="post" action="" autocomplete="off" onsubmit="return submitData();"> <label>Name:</label> <input type="text" name="name" id="name" class="stored" value=""> <br/> <label>Message:</label> <textarea name="message" id="message" class="stored"></textarea> <br/> <input type="submit" class="demo-button" value="Submit"> </form> <br/> <input type="button" class="btn-clear" value="Clear Local Storage" onclick="clearStorage();"> <script> function lsTest(){ var i = 'test'; try { localStorage.setItem(i, i); localStorage.removeItem(i); return true; } catch(e) { return false; } } function populateData() { if(lsTest() === true){ var retrievedObject = localStorage.getItem('testObject'); document.getElementById('myspan').innerHTML = 'available.'; document.getElementById('myCount').innerHTML = localStorage.length; document.getElementById('myResult').innerHTML = retrievedObject; console.log('retrievedObject: ', JSON.parse(retrievedObject)); }else{ document.getElementById('myspan').innerHTML = 'unavailable.'; } } populateData(); function submitData(){ var v_name = document.getElementById('name').value; var v_message = document.getElementById('message').value; var testObject = { 'name': v_name, 'message': v_message }; localStorage.setItem('testObject', JSON.stringify(testObject)); //localStorage.setItem('message', v_message); alert('Data: '+localStorage.getItem('testObject')); populateData(); return false; } function clearStorage(){ localStorage.clear(); populateData(); } </script> </body> </html> 

If you're using onclick set input type as button

<input type="button" class="btn-clear" value="Clear Local Storage" onclick="submitData();">

or else use onsubmit

<form onsubmit="return submitData()">
</form>

<script>
function submitData() {
    // Your work

    // Make sure it returns false to prevent form from reloading the page
    return false;
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM