Dominique Deschatre
Dominique Deschatre

Reputation: 119

jQuery incrementing ids of cloned descendents by 1

I have the following jQuery function:

$(document).ready(function(){
    $("#nmovimentos").change(function () {
        var direction = this.defaultValue < this.value
        this.defaultValue = this.value;
        if (direction) {
            var $div = $('div[id^="novomov"]:last');
            var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;
            var $clone = $div.clone().prop('id', 'novomov'+ num)
            $clone.insertAfter('[id^="novomov"]:last');
            $('[id^="darktheme"]:last').text('+ '+num+'º Novo Movimento');
            // get all the inputs inside the clone
            $clone.find('*').each(function() {
                var name = $(this).prop('name');
                var id = $(this).prop('id');
                $(this).prop('name', name+num);
                $(this).prop('id', id+num);
            });
        }
        else {
            $('[id^="novomov"]:last').remove();
        }
    });
});

Basically, it clones the div element with id="novomov1"and increments the number at the end everytime. So, for the 1st clone, the id is id=novomov2. It was suppossed to do the same thing for all the names and ids of the clone's descendents, but it is only working with the names. For the descendent's ids, the numbers at the end are not being added, they are being placed at the end of the number. For example, an id="mov1" becomes id="mov12", id="mov123" and so on... Why is that occuring if the code is the same for the names and ids?

<div id="novomov1">
    <table>
        <tr>    
            <td id="darktheme1"> +New Moviment</td>
        </tr>
    </table>

    <table id="tabela1">
        <tr>
            <td id="mov1">
                Type:<br>
                <input name="tipomov1" id="l1" type="radio" value="1" >Line</input>
                <input name="tipomov1" id="c1" type="radio" value="2" >Circle</input>
                <input name="tipomov1" id="r1" type="radio" value="3" >Rotate</input>
                <input name="tipomov1" id="m1" type="radio" value="4" >Move</input>
            </td>
        </tr>
    </table>
</div>

Upvotes: 1

Views: 149

Answers (1)

nurdyguy
nurdyguy

Reputation: 2945

In this line:

    $(this).prop('id', id+num)

your id is a string so instead of adding the values numerically, it concatinates the value as a string. That's why mov1 becomes mov12. To fix this you need to mimic what is done above in:

    var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

The parseInt turns it into an integer so it is numerical addition instead of string concatination. Such is the fundamental issue with "loosely typed" languages like javascript.

Upvotes: 1

Related Questions