0

i'm working on a form and having some problems.

I have a input field that when changed to a higher or lower number it adds/removes extra fields but if type something into one of the extra fields and add an additional one it removes all values where it should be saving the values

js:

var eh = document.getElementById('ulId');//list to add list items to
var ac = document.getElementById('inputId');

var defaultId = "xin";

//x is short extra
var anyXFields = false;
var XF = 0;//extra fields
var lastXField = 0;
var mostFields = 0;
var index = [];


function hideInputFields(n) {

    if (lastXField < n) {
        return;
    }else if(lastXField > n) {
        $("#xin" + lastXField).hide();
    }
}


//on change function
function oc() {

    n = ac.value;
    n = parseInt(n);

    lastXField = n - 1;

    if (n > 0) {

        if (anyXFields) {
            hideInputFields(n - 2);
        }

        for (i = 0; i < (n - 1); i++) {
            if (i < mostFields) {
                $("#xin" + i).show();
            } else if (!index[i]) {
                eh.innerHTML += '<li id="'+(defaultId + i)+'"><label>Højde' + (i + 2) +' <label class="sub">Height' + (i + 2) +'</label></label><input name="'+(defaultId + i)+'" class="inputfield"></li>';
                index[i] = 1;
            }
        }

        if (mostFields < (n - 1)) {
            mostFields = n - 1;
        }

        anyXFields = true;
    }

}
  • You should share your html code too, and provide a jsfiddle or something like that if it's just javascript and html – Yerko Palma Aug 11 '15 at 14:21

2 Answers2

0

You are creating the list elements with innerHTML. Every time you run oc(), all of the list items are remade from the predefined string inside oc(), the data you have typed into the input elements are not saved to that string so they will be lost.

A solution/better way to achieve what you want to achieve is to use a for loop to create the list items and only remove the 'extra' input elements instead of remaking all of them on change.

Huan Zhang
  • 1,095
  • 8
  • 13
0

If you are trying to append to a list and removing you can use .appendTo(...) or .remove in jquery rather than using inner html.

Ajmal E S
  • 57
  • 4