0

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+"][]");


        });

});
3
  • OP has already added JsFiddle Commented Jan 16, 2014 at 18:43
  • Bah, Didn't see that. Thanks! Commented Jan 16, 2014 at 18:44
  • I've linked Fiddle Link also here, to find it quickly :) Commented Jan 16, 2014 at 19:01

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your answer, where is it better to place your for loop code inside my script?
Doesn't matter much... Maybe between the two lines var FieldCount = $('#MetricsCnt').val(); and FieldCount--;
I don't understand well how modify the input ids with that for, sorry :)
The for loop goes through every number that is above the number of the removed metric and therefore shall be decreased.
@Markviduka: There was a bug in my code regarding the numRemoved because it got "metric-x" instead of the actual number x. I also updated your fiddle here: fiddle.jshell.net/5RaG3/1 (Note that I only changed the id of the div and the name of the input, you can add more changes in a similar way.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.