Create indexes dynamically with javascript

Asked

Viewed 111 times

1

Good morning gentlemen,

I’m creating a system of contracts and I’m having a question of how to realize a certain idea.

How the contract works by closures and paragraphs, I need to add indexes dynamically.

The idea would be 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, that is to say it does not write to a database and receives nothing from a database, so if the user deletes the paragraph 2.1 for example, the paragraph 2.2 automatically becomes 2.1.

Good any idea already helps enough, I thank you! Hug!

  • 1

    If you do not use bank, where are you recording? Or if you can give more details, I did not understand the question right.

1 answer

2


You can use a Regexp to find indexes and replace them in ascending order. It would be 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: http://jsfiddle.net/9hh5amko/

Javascript has a native function for substitutions. Passing it a function as a second parameter you can work each value found by regex.

Within the function separated into 2 types. Those who have . (subIndex) and what they don’t have (currentIndex) and this way they increase leaving everything ordered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.