NoMadic NoMadic - 1 year ago 68
HTML Question

Increment element Id upon cloning a row in Javascript

I have a HTML page where in one row has 2 dropdown elements and one text input element. I added a button to clone this row successfully. I added another button for an action POST to push all the dropdown and textinput values to the database. Problem here is while cloning, the Id of the elements in the row are cloned too - so I am unable to fetch the values.

My HTML Code:

<div class="rule">
<div class="form-group">

<div class="col-md-3 col-sm-3 col-xs-3">
<select class="form-control" name="condition" id="condition">
<option value="">Choose Sensor</option>

<div class="col-md-3 col-sm-3 col-xs-3">
<select class="form-control" name="paraop" id="paraop">
<option>Choose Condition</option>
<option>Equal to</option>
<option>Less than</option>
<option>Greater than</option>

<div class="col-md-3 col-sm-3 col-xs-3">
<input type="text" required="true" placeholder="Value..." class="form-control" name="value" id="value">

<div class="rule-options">
<a href="#" class="add-rule-btn"><i class="fa fa-plus-circle"></i></a>
<a href="#" class="remove-rule-btn"><i class="fa fa-times-circle"></i></a>

The elements cloned are "condition", "paraop" and "value".

Javascript code to clone:

handleAddRule: function() {

var _self = this;

$('.add-rule-btn').live('click', function() {
var parentRuleGroup = $(this).parents('.rule');
var newRule = $('.rule:first').clone();


return false;

I am thinking of incrementing the element Ids everytime I press the add button- So I can easily fetch the elements by their Ids from the POST php file. But how can I increment the Id value? Or is there any another way to retrieve the elements from the POST page?

Answer Source

Got this to work. All I needed was this additional block in javascript which will find the inputs and append an incremented number to it.

 newRule.find(':input').attr('id', function(i, val) {
        return val + count;

Based on the answer here to this question Clone form and increment ID

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download