alessandrob
alessandrob

Reputation: 1615

jQuery - Update input name and id based on counter value

I've the following html with a counter that takes number of times a button named "Add Metric" it's pressed. I will use this numeric value to assign it to some html created by pressing button itself.

I've no problem adding elements, the counter works well. Problems are when I need to delete something in the middle of all generated content. For instance consider the case when I press 4 times the "Add Metric" button, code generated will be:

<div id="metric-0"> .... </div>
<div id="metric-1">
  .... 
  <input type="text" name="metrics[1][name]" value="Text 1"></div>
  ....  
</div>
<div id="metric-2">
  .... 
  <input type="text" name="metrics[2][name]" value="Text 2"></div>
  ....
<div id="metric-3"> .... </div>

If i need to delete, let's say, the second div (<div id="metric-1">), I would obtain this:

<div id="metric-0"> .... </div>
<div id="metric-1"> 
  .... 
  <input type="text" name="metrics[1][name]" value="Text 1"></div>
  ....   
</div>
<div id="metric-2"> .... </div>

Where metric-2 and metric-3 are transformed in metric-1 and metric-2

Anyway, I don't understand where I'm wrong and I can obtain only this case, when all divs maintain their name

<div id="metric-0"> .... </div>
<div id="metric-2"> .... 
  .... 
  <input type="text" name="metrics[2][name]" value="Text 2"></div>
  ....  
</div>
<div id="metric-3"> .... </div>

Question: There's a solution to fix this problem? Here's the fiddle

Here's the HTML:

<div id="InputsWrapper">
      <input type="button" id="AddMoreFileBox" value="Add Metric">
      MetricsCounter: <input type="text" id="MetricsCnt" value="-1" />
</div>

This is jQuery Code:

$(document).ready(function() {
    /*
     * Add Metric Button
     */
    $("#AddMoreFileBox").click(function (){ 
        var FieldCount = $('#MetricsCnt').val();
        FieldCount++;
        $('#MetricsCnt').val(FieldCount);
        $("#InputsWrapper").append
            ('<div id="metric-'+FieldCount+'">'
            +'Metric:<input type="text" name="metrics['+ FieldCount +'][name]" value="Text '+ FieldCount+'"/><br/>'
            +'<label>Tags:</label><br/>'
            +'<div id="tags-'+FieldCount+'">'
            +'<input type="button" class="addtag" id="'+FieldCount+'" value="+ Tag">'
            +'<input type="hidden" id="AddBox'+FieldCount+'" value="-1" />'
            +'</div>'
            +'<label>Aggregator:</label><br/>'
            +'<div id="aggregators-'+FieldCount+'">' // Aggregators-0 prima volta
            +'<input type="button" class="agg" id="'+FieldCount+'" value="+ Aggregator">'
            +'<input type="hidden" id="AggBox'+FieldCount+'" value="-1" />'
            +'</div>'
            +'<a href="#" class="removeclass">&times;</a></div>');
    return false;
    });

    /*
     * Delete a Metric
     */
    $("body").on("click",".removeclass", function(e){ //user click on remove text
        $(this).parent('div').remove(); //remove text box
        var FieldCount = $('#MetricsCnt').val();
        FieldCount--;
        $('#MetricsCnt').val(FieldCount);
    return false;
    });
    /*
     * AddTag Button
     */
    //var valueCnt = 0;
    $("#InputsWrapper").on('click', ".addtag", function (){  
        var idTags = $(this).attr('id');
        var tagCounter = $('#AddBox'+idTags).val();
        tagCounter++;
        $('#AddBox'+idTags).val(tagCounter);
        $('#tags-'+idTags).append
        ('Id: <input type="text" class="tagsIdentifier" id="TagId-'+idTags+tagCounter+'" />'+ //OK 
         'Value: <input type="text" class="tagValues-'+idTags+tagCounter+'" id="TagValue-'+idTags+tagCounter+'" name="metrics['+idTags+'][tags][][]" /></div><br/>');
        //return false;
    });

    /*
     * Add Aggregator Button
     */
    $("#InputsWrapper").on('click', ".agg", function(){
        var ids = $(this).attr('id');
        //alert(ids);
        var aggCounter = $('#AggBox'+ids).val();
        aggCounter++;
        $('#AggBox'+ids).val(aggCounter); 
        $('#aggregators-'+ids).append(
                'Type: <input type="text" name="metrics['+ids+'][aggregators]['+aggCounter+'][name]" />'+
                'Sampling: <input type="text" name="metrics['+ids+'][aggregators]['+aggCounter+'][sampling][value]" />'+
                '<input type="text" name="metrics['+ids+'][aggregators]['+aggCounter+'][sampling][unit]" /><br/>');
        return false;
       });

    /*
     * Updates every tagID change using the mouseleave function
     */
    $('#InputsWrapper').on('mouseleave', '.tagsIdentifier', function(){
            var tagIdentifierId = $(this).attr('id'); 
            var provaId=$(this).attr("id").split("-"); 
            var tagIdValue = $(this).val(); 
            $('#TagValue-'+provaId[1]).attr("name","metrics["+provaId[1].charAt(0)+"][tags]["+tagIdValue+"][]");


        });

});

Upvotes: 0

Views: 711

Answers (1)

Thomas Leu
Thomas Leu

Reputation: 855

The answer to your question is yes. The howto is pretty straightforward, though it is a bit inconvenient... The approach is the following: When removing a metric, get the number of the removed metric by something like

var numRemoved = parseInt($(this).parent('div')[0].id.substr(7));

(Obviously this line has to stand before removing the div.)

Then rename all following metrics and whatsoever in a loop like:

for (var i = numRemoved + 1; i <= FieldCount; i++) {
  // rename objects
  var metric = $("#metric-" + i);
  metric[0].id = "metric-" + (i - 1);
  metric.find(...).attr('name', ...);
  ...
}

(FieldCount here is before decreasing it.)

Upvotes: 1

Related Questions