1

So I have a textfield, a button for adding the text to localstorage and a button to remove it.

This is my script:

function save() {
    var fieldValue = document.getElementById('textfield').value;
    localStorage.setItem('text', fieldValue);
}


function load() {
    var storedValue = localStorage.getItem('text');
    if(storedValue) {
        document.getElementById('textfield').value = storedValue;
    }
}


function remove() {

    document.getElementById('textfield').value = '';
    localStorage.removeItem('text');

}

The save and load functions both work, but when I click the "remove button", it removes the button itself instead of the local storage value.

user2971812
  • 379
  • 2
  • 3
  • 9

1 Answers1

3

remove() seems to be a reserved function name in Javascript. If you call it using onclick for example, it will just remove the element rather than call the defined function.

I created a fiddle to demonstrate the issue: http://jsfiddle.net/mW644/

If you inspect the function using <button onclick="alert(remove)">Test</button> you get a native function instead of the one you defined:

function remove() {
    [native code]
}

Rename remove() to something else and it will work fine.

nullability
  • 10,545
  • 3
  • 45
  • 63
  • `.remove()` is a jQuery method to remove the element from the DOM, so it may be a consequence of him having jQuery loaded (although he doesn't say if he included it or not so I'm not certain). – Ennui Nov 15 '13 at 21:52
  • My fiddle does not have jQuery loaded and it still happens. It's actually a native function. – nullability Nov 15 '13 at 21:54
  • 2
    Here: http://stackoverflow.com/questions/16151295/is-remove-a-reserved-keyword-in-google-chrome –  Nov 15 '13 at 21:59