Muhammad
Muhammad

Reputation: 634

JQuery: Finding a way to name cloned input fields

I'm not the best at using jQuery, but I do require it to be able to make my website user-friendly.

I have several tables involved in my website, and for each the user should be able to add/delete rows. I created a jquery function, with help from stackoverflow, and it successfully added/deleted rows. Now the only problem with this is the names for those input fields is slightly messed up. I would like each input field to be an array: so like name[0] for the first row, name[1] for the second row, etc. I have a bunch of tables all with different inputs, so how would I make jQuery adjust the names accordingly?

My function, doesn't work completely, but I do not know how to go about changing it.

My Jquery function looks like:

$(document).ready(function() {
  $("body").on('click', '.add_row', function() {
    var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
    var clone = tr.clone();
    clone.find("input").val('');
    clone.find("select").val('');

    clone.find('input').each(function(i) {
    $(this).attr('name', $(this).attr('name') + i);
  });

  clone.find('select').each(function(i) {
     $(this).attr('name', $(this).attr('name') + i);
  });

  tr.after(clone);
  });

  $("body").on('click', '.delete_row', function() {
     var rowCount = $(this).closest('.row').prev('table').find('tr.ia_table').length;
     var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
     if (rowCount > 1) {
         tr.remove();
     };
  });
});

I also created a jsFiddle here: https://jsfiddle.net/tareenmj/err73gLL/.

Any help is greatly appreciated.

UPDATE - Partial Working Solution

After help from a lot of users, I was able to create a function which does this:

$("body").on('click', '.add_row', function() {
  var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
  var clone = tr.clone();
  clone.find("input").val('');
  clone.find("select").val('');

  clone.find('input').each(function() {
      var msg=$(this).attr('name');
      var x=parseInt(msg.split('[').pop().split(']').shift());
      var test=msg.substr(0,msg.indexOf('['))+"[";
      x++;
      x=x.toString();
      test=test+x+"]";
      $(this).attr('name', test);
      
  });

  clone.find('select').each(function() {
      var msg1=$(this).attr('name');
      var x1=parseInt(msg1.split('[').pop().split(']').shift());
      var test1=msg1.substr(0,msg1.indexOf('['))+"[";
      x1++;
      x1=x1.toString();
      test1=test1+x1+"]";
      $(this).attr('name', test1);
  });

  tr.after(clone);

});

A working jsFiddle is here: https://jsfiddle.net/tareenmj/amojyjjn/2/

The only problem is that if I do not select any of the options in the select inputs, it doesn't provide me with a value of null, whereas it should. Any tips on fixing this issue?

Upvotes: 3

Views: 364

Answers (2)

Muhammad
Muhammad

Reputation: 634

Full Working Solution for Anyone Who needs it

So after doing loads and loads of research, I found a very simple way on how to do this. Instead of manually adjusting the name of the array, I realised that the clone method will do it automatically for you if you supply an array as the name. So something like name="name[]" will end up working. The brackets without any text has to be there. Explanation can't possible describe the code fully, so here is the JQuery code required for this behaviour to work:

$(document).ready(function() {

$("body").on('click', '.add_row', function() {
  var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
  var clone = tr.clone();
  clone.find("input").val('');

  tr.after(clone);
});

$("body").on('click', '.delete_row', function() {
   var rowCount = 
   $(this).closest('.row').prev('table').find('tr.ia_table').length;
     var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
     if (rowCount > 1) {
       tr.remove();
     };
});
});

A fully working JSfiddle is provided here: https://jsfiddle.net/tareenmj/amojyjjn/5/

Just a tip, that you have to be remove the disabled select since this will not pass a value of null.

Upvotes: 1

buydadip
buydadip

Reputation: 9437

I think I understand your problem. See if this fiddle works for you...

This is what I did, inside each of the clone.find() functions, I added the following logic...

clone.find('input').each(function(i) {
    // extract the number part of the name
    number = parseInt($(this).attr('name').substr($(this).attr('name').indexOf("_") + 1));
    // increment the number
    number += 1;
    // extract the name itself (without the row index)
    name = $(this).attr('name').substr(0, $(this).attr('name').indexOf('_'));
    // add the row index to the string
    $(this).attr('name', name + "_" + number);
});

In essence, I separate the name into 2 parts based on the _, the string and the row index. I increment the row index every time the add_row is called.

So each row will have something like the following structure when a row is added...

 // row 1
 sectionTB1_1
 presentationTB1_1
 percentageTB1_1
 courseTB1_1
 sessionTB1_1
 reqElecTB1_1

 // row 2
 sectionTB1_2
 presentationTB1_2
 percentageTB1_2
 courseTB1_2
 sessionTB1_2
 reqElecTB1_2

 // etc.

Let me know if this is what you were looking for.

Upvotes: 1

Related Questions