Kamil Kamil - 2 months ago 8x
HTML Question

javascript substring like backspace

HI in the code down below i have a html setup with buttons for a password input form:

<meta charset="utf-8">
<title>Log in form</title>
<link href="style.css" rel="stylesheet">
<script src="ui.js"></script>
<div id="main">
<div id="top_bar"><tx id="tx">Bildschirmsperre</tx></div>
<div id="infotext">Wählen sie Ihre PIN aus</div><br />
<div id="pin"></div><button id="btnback" onclick="changepin(10)">&larr;</button><br />

<div id="tasten">
<button class="button" onclick="changepin(1)">1</button>
<button class="button" onclick="changepin(2)">2</button>
<button class="button" onclick="changepin(3)">3</button><br />
<button class="button" onclick="changepin(4)">4</button>
<button class="button" onclick="changepin(5)">5</button>
<button class="button" onclick="changepin(6)">6</button><br />
<button class="button" onclick="changepin(7)">7</button>
<button class="button" onclick="changepin(8)">8</button>
<button class="button" onclick="changepin(9)">9</button><br />
<button class="button" onclick="changepin(0)">0</button>
<div id="bottom_bar"> <text id="text_left">ABBRECHEN</text> <zeichen id="zeichen">|</zeichen> <text id="text_right">WEITER</text> </div>

There is no css so it looks awful right now and it contains words in germany so please ignore them.

so far i have this javascript:

var count = 0;

function changepin(value) {
var pin = document.getElementById("pin");
if(value != 10 && count < 4){
pin.innerHTML += value;
}else if(value == 10){
pin.innerHTML = pin.value.substr(0, count);

the typing in (max 4 letters) works fine but i have no idea how to make the backspace i tried a little bit but it isnt working.

Could anyone pls help?



You almost had it, but the use of the count variable is both unnecessary and potentially confusing. This does what you need, without it...

// only do this once - no need to find the element every time
var pin = document.getElementById("pin");

function changepin(value) {
    var currentPin = pin.innerText;

    // if user pressed the back button then remove the last character
    if (value == 10) {
        pin.innerText = currentPin.substr(0, currentPin.length - 1);
    // else if the current pin is long enough then just exit without doing anything else
    else if (currentPin.length > 3) {
    // else add the new character to the pin
    else {
        pin.innerText = currentPin + value;

As you can see I also changed innerHTML to innerText. In this case it makes no difference, but it's good habit to always refer to the correct property, so you want to set the text, not the HTML.