-1

I got a small problem, I'm trying to save the values of the input field "a1" into localstorage, but for some reason it's not saving. I can't seem to figure out what the problem is...

All help is appreciated!

FIXED: Place the script at the bottom.

    <!DOCTYPE html>
<html>
<head>
    <script src="jquery.js"></script>
    <script>
        document.getElementById('a1').onkeyup = function() {
            var a1 = document.getElementById('a1').value;
            localStorage.setItem('a1', a1);
        };
    </script>
    <link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>

<div class="box">
    <div class="title">Kalkulator</div>
    <div class="text">Antal kvadratmeter: <input class="input-field" id="a1" type="text" value="0" /> m2</div> <---- HERE
    <div class="text">Kantklipp rundt plenen? (+3.00kr per m): <input class="input-field" id="a2" type="text" value="0" /> m</div>
    <div class="text">Gjødsel? (+1.00kr per kvm) <input class="input-field2" type="checkbox" name="checkbox" id="checkbox_check2"></div>
    <div class="text">Mosefjerning? (+2.00kr per kvm) <input class="input-field2" type="checkbox" name="checkbox" id="checkbox_check3"></div>
    <div class="text">Pris (kr) <input class="input-field3" id="a4" type="text" value="0.00" /></div>
    <div class="text2">Obs! Minstepris på 300kr.</div>
    <div class="tilbud-knapp">Legg til i tilbuds liste</div>
    <div class="border"></div>
</div>
Seb
  • 523
  • 1
  • 5
  • 23
  • 1
    @Carcigenicate, i saw this first now, error in console "(index):6 Uncaught TypeError: Cannot set property 'onkeyup' of null". – Seb Sep 06 '17 at 12:12

1 Answers1

3

Place your code at the bottom of the page. It's running before the elements are rendered, which means the event can't be registered to the element.

Broken:

<script>
    document.getElementById('a1').onkeyup = function() {
        var a1 = document.getElementById('a1').value;
        localStorage.setItem('a1', a1);
    };
</script>
<input class="input-field" id="a1" type="text" value="0" /> 

Fixed (except localStorage ins't usable in snippets):

<input class="input-field" id="a1" type="text" value="0" /> 
<script>
    document.getElementById('a1').onkeyup = function() {
        var a1 = document.getElementById('a1').value;
        localStorage.setItem('a1', a1);
    };
</script>
Cerbrus
  • 60,471
  • 15
  • 115
  • 132