Create indexes dynamically with javascript

1

Good morning, gentlemen,

I'm creating a system of contracts and I have a question about how to come up with a certain idea.

Because the contract works by clocks and paragraphs, I need to add indexes dynamically.

The idea would look like this:

1 - Primeira Clausura.
1.1 - Primeiro paragrafo.
1.2 - Segundo Paragrafo
...

2 - Segunda Clausura.
2.1 - Primeiro paragrafo da segunda clausura.
2.2 - Segundo paragrafo da segunda clausura.
...

3 - Terceira Clausura.
3.1 - Terceiro paragrafo da Terceira clausura.
3.2 - STerceiro paragrafo da Terceira clausura.
...

I have a js function that adds these paragraphs through a textarea, ie does not write to a bank and does not receive anything from a bank, so if the user deletes the paragraph 2.1 for example, the 2.2 paragraph goes automatically to be 2.1 .

Well any idea already helps a lot, thank you! Hugs!

    
asked by anonymous 24.07.2015 / 15:31

1 answer

2

You can use a RegExp to browse indexes and replace them in ascending order. It would look something like this:

var textarea = document.getElementById('contrato');
var clausulas = new RegExp('([0-9\.]+)\s\-', 'g');
textarea.addEventListener('keyup', function () {
    var texto = this.value;
    var currentIndex = 0;
    var subIndex = 0;
    this.value = texto.replace(clausulas, function (match) {
        if (match.indexOf('.') == -1) {
            currentIndex++;
            subIndex = 0;
            return currentIndex + ' -';
        }
        subIndex++;
        return [currentIndex, '.', subIndex, ' -'].join('');
    });
});

jsFiddle: link

JavaScript has a native function for overrides. Passing a function as second parameter you can work each value found by regex.

Inside the function I separated into 2 types. Those that have . (subIndex) and what they do not have (currentIndex) and in this way they increase by leaving everything in order.

    
25.07.2015 / 22:11