mardi 14 juin 2016

Values selected in select box cannot be retrieved- JQuery

I am building an application in which I have table with form elements like select, input etc.

All I want is to populate the values selected in form elements to another table.

You can find my code here

JS :

 $('button').click(function() {
  var rows = $('#table1 tbody tr');
  var previewTable = $('#table2 tbody');
  previewTable.find('tr').remove();
  for (var i = 0; i < rows.length; i++) {
   var tr = $('<tr> </tr>');
   previewTable.append(tr);
   var row_cloned = $(rows[i]).clone();
   var cols = rows[i].getElementsByTagName("td");
   for (var j = 0; j < cols.length; j++) {
    var col_cloned = row_cloned.find('td').clone();
    previewTable.find('tr').eq(i).append(col_cloned[j]);


    if ($(col_cloned[j]).children().length > 0) {
     $(col_cloned[j]).children().each(function(index, item) {
      if ($(item).is('select')) {
        if ($(item).attr('multiple')) {
          var foo = [];
          $(item).each(function(i, selected) {
            console.log($(selected).val());
            foo[i] = $(selected).val();
          });
          $(col_cloned[j]).text(foo);
        } else {
          $(col_cloned[j]).text($(item).val());
        }

      } else if ($(item).is('label')) {
        var selected = [];
        $(item).find('input:checked').each(function(index, item) {
          selected.push($(item).val());
          $(col_cloned[j]).append(selected + '<br>');
        })
      }
    })
  } else {
    $(col_cloned[j]).text($(col_cloned[j]).text());
    }
   }
  }
})

My steps:

  1. Get table1 and table2
  2. Count the number of rows in the table1
  3. Add so many empty rows in the table2
  4. Get each row in table1
  5. Count the td in each row of table1
  6. Find the children in each td
  7. Check if children is select, input, or just plain text
  8. If children is select, determine if it is multi-select or single
  9. Act accordingly for each form elements to copy only values and then append to table2
  10. finish

All this on a button click COPY

Problem: Somehow managed to get the checked input form element values. But failing to get the values selected in select box.

For multi select box my code:

if ($(item).attr('multiple')) {
      var foo = [];
      $(item).each(function(i, selected) {
        console.log($(selected).val());
        foo[i] = $(selected).val();
      });
      $(col_cloned[j]).text(foo);
    }

For single select box :

else {
      $(col_cloned[j]).text($(item).val());
    }

What is my mistake exactly? Thanks in Advance

Aucun commentaire:

Enregistrer un commentaire