Skip to content Skip to sidebar Skip to footer

Increment Index Of A Javascript Function's Argument Name Dynamically

In this code javascript function is taking from[1] as argument in displayDatePicker('from[1]', false, 'dmy', '-'). When I clone this (second) row using jquery, all my input and sel

Solution 1:

Drop the id attributes in your <input>s, you don't need them and having duplicate ids just leaves you with invalid HTML and strange problems. If you're using them for styling, use classes instead. If you need them for something else, then you'll have to fix them when you copy so that you don't end up with duplicate ids.

Now we can clean up your cloning a little bit. When you're cloning your row, you don't need to parse the number in brackets, you can just ask the table how many rows it has and add one to get the new number:

var n = $('#table2 tbody>tr').length + 1;

then your replace calls simplify to this:

this.name.replace(/\[(\d+)\]$/, '[' + n + ']');

Also, you can use a multiple-selector to iterate through the <input>s and the <select>s at the same time:

row.find('input:text, select').each(...)

You're changing the same attribute in both cases so there's no need for two identical loops.

Using javascript:displayDatePicker(...) in your <a> isn't necessary. You can use jQuery to bind to clicks on those <a>s by adding a class to them:

<a class="datepicker">...</a>

and then binding a callback to them using click and a closest/find combination inside the callback will let you find the corresponding <input>:

$('a.datepicker').click(function() {
    var $input = $(this).closest('td').find('input[type=text]');
    displayDatePicker($input.attr('name'), false, 'dmy', '-'));
});

You're using clone so the event handlers on the cloned elements will be copied so you don't have to mess around with delegate or the dynamic versions of on.

Here's a demo with simplified HTML: http://jsfiddle.net/ambiguous/yEaw6/


Solution 2:

From what I have understood from the first paragraph in your question..

Will this help?

var cells = $('td');  //Select row/cells here

$.each(cells, function(index, cell){
  //index corresponds to index of current cell in set of matched cells  
});

Post a Comment for "Increment Index Of A Javascript Function's Argument Name Dynamically"