Jquery Array only outputting the first value in dialog

I am trying to pass an array to jquery dialog from a checkbox, but it only outputs the second value when there are 2 in the array. In console.log when I submit the array, it shows like so which as you can see contains 2 values but dialog only prints the second value. This is following on from a previous post outlining a similar problem which I never solved.

Array(10) [ "14", "Standard", "New Box Intake", "DEMO", "DEMO", "22 London Road  Charles House   London W12 3RT ", "Demo User", "DEMOBOX0014", "N/A", "14/01/2033" ]
Array(10) [ "16", "Standard", "New Box Intake", "DEMO", "DEMO", "22 London Road  Charles House   London W12 3RT ", "Demo User", "DEMOBOX0016", "N/A", "14/01/2033" ]

I would be grateful if someone could check my code and help me to understand my mistake as I am quite new to jquery. Many thanks.

Dialog code

$(function() {
  //$(".defaultBtn").prop('disabled',true);
  $('#rack').dialog({
    autoOpen: false,
    title: 'New Intake Slot Assingment',
    height: 520,
    width: '50%',
    modal: true,
    resizable: false,
    position: {
      my: 'top',
      at: 'top+35'
    },
    open: function(event, ui) {
      $('#rack').css('overflow', 'hidden'); //this line does the actual hiding
      $(info).each(function(index, data) { // should open an array here
        console.log(data);
      });
    },
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "blind",
      duration: 1500
    },
    buttons: [{
      text: "Submit",
      "class": 'defaultBtn',
      click: function(e) {
        e.preventDefault();
        var data = $('#rack').serialize();
        console.log(data);
        $.ajax({
          type: 'POST',
          url: '/lsorg/admin/niajax.php',
          data: data,
          async: false,
          beforeSend: function() {
            $(".text").show().html('Processing your request...');
          },
          success: function(data) {
            if (data.trim() == 'All fields must be completed') {
              $(".text").html('ERROR: You must complete all fields for the slot assignment.').css({
                "color": "red",
                "font-size": "13px",
                "margin-left": "21px"
              });
              return false;
            } else {
              $.get('/lsorg/admin/refreshActions.php?count=' + 'Actions', function(data) {
                //console.log(data);
                $(".actions").text(data);
              });
              $.get('/lsorg/admin/refreshActions.php?count=' + 'New Box Intake', function(data) {
                //console.log(data);
                $(".ni").text(data);
              });
              $("#rack").dialog("close");
              activity = 'New box Intake Assignment';
              showModelActionSuccess(data);
              $(".text").empty();
              $("#rack").trigger("reset");
              tableni.ajax.reload(null, false);
              return false;
            }
          },
          error: function(xhr) {
            $(".text").fadeIn(4000).html('Error occured.please try again').fadeOut(4000);
          },
          complete: function() {},
        })
      }
    }, {
      text: "Cancel",
      "class": 'defaultBtnClose',
      click: function() {
        $(this).dialog("close");
        $("#rack").trigger("reset");
        $(".text").empty();
      }
    }, ],
    close: function() {
      $("#rack").trigger("reset");
      $(".text").empty();
      $(".chosen-select").attr("data-placeholder", "Select a box size").val('').trigger('chosen:updated');
    }
  });
});

jquery code

$(function() {
  $(document).on('click', '.rowChk', function() {
    currentRows = $(this).closest("tr");
    rackid = currentRows.find("td:eq(0)").html();
    rackservice = currentRows.find("td:eq(2)").html();
    rackactivity = currentRows.find("td:eq(3)").html();
    rackdept = currentRows.find("td:eq(4)").html();
    rackcompany = currentRows.find("td:eq(5)").html();
    rackaddress = currentRows.find("td:eq(6)").html();
    rackuser = currentRows.find("td:eq(7)").html();
    rackitem = currentRows.find("td:eq(8)").html();
    //rackboxsize = currentRows.find("td:eq(8)").html();
    rackddate = currentRows.find("td:eq(9)").html();
    rackdate = currentRows.find("td:eq(10)").html();
    info = [];
    info[0] = rackid;
    info[1] = rackservice;
    info[2] = rackactivity;
    info[3] = rackdept;
    info[4] = rackcompany;
    info[5] = rackaddress;
    info[6] = rackuser;
    info[7] = rackitem;
    info[8] = rackddate;
    info[9] = rackdate;
  });
});

pass array values to dialog

$(document).on('click', '#rowClk', function() {
  $("#rack").dialog("open");
    $("#rack_id").val(info[0]);
    $("#rack_service").val(info[1]);
    $("#rack_activity").val(info[2]);
    $("#rack_dept").val(info[3]);
    $("#rack_company").val(info[4]);
    $("#rack_address").val(info[5]);
    $("#rack_user").val(info[6]);
    $("#rack_item").val(info[7]);
    $("#rack_datetimepicker").val(info[8]);
    $("#rack_ddatetimepicker").val(info[9]);
    console.dir(info);
});

It is only outputting 1 value in console.log. Do I have to run an each function here or is the code correct.

Hi,

I’m afraid I have no idea. When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem.

I would suggest reading this, then posting back here with a minimal, complete, and verifiable example (see link). If you can do this, then I’d be happy to take a look.

2 Likes

So… first off. It would be more helpful to see your final HTML for the dialog (inspect the element while it’s open on screen) than the dialog code itself.

Second of all:
Where are your definitions for elements ‘rowChk’ and ‘rowClk’? Why is rowClk an ID instead of a class?

Thanks for reply. What I am basically trying to do is put values of the ‘.rowChk’ into an array to pass to dialog for the ajax call. To try and make this work, how would i put those values into an array. Thanks

Thanks for the heads up.

You’ve put them into an array. But your code only looks for the nearest row to read values from. If you want to read all of the rows, you’d .each a selector that pulls all of the table’s data rows.

Could you please provide an example as I am struggling with this. Thanks

Well, let’s give it a try in stages.

You’ve already got code for what to do with a row; though since we’re now establishing an array of rows, you’ll need to append the row’s value array to the overall array (or better yet, use an array of objects instead of an array of arrays.)

So, there are three basic steps:
1: Select all rows of the table. You’ve got enough examples of selectors in your code already that you should be able to do this.
2: .each that selector, and run the code you’ve already got.
3: add the array created in step 2 to another array, that holds your data arrays.

Which of the three are you struggling with?

2: .each that selector, and run the code you’ve already got.

.each what selector?

3: add the array created in step 2 to another array, that holds your data arrays.

You have lost me here. Could you do visual even if it is not my code. Thanks

the selector from step 1.

the elements of arrays can be any Javascript construct - including other arrays. (“Array Elements Can Be Objects” section)

Guess you aren’t going to do example so I shall follow your link and see if I can figure it out. Many thanks

Yes, i’m not going to write your code for you, that way in 3 weeks when you still havent learned from copy and pasting other peoples’ code, you dont expect me to adjust my code to fix your new problem.

If you don’t understand the code you’ve taken from elsewhere, i’d suggest you stop trying to do new things and figure out what you’ve got now.

Firstly, I haven’t taken ode from anywhere and if you read my comment, I asked for an example not based on my code. How else is one expected to learn. Many thanks for your help.

By actually following the instructions given. I invite you to go reread post 8 again, try the three steps there, and come back with your attempt, which we will gladly help you refine. I even asked you in that post which of the three you were struggling with.
Or you can keep insisting “do it for me”. shrug
And yes, “write me an example” is “do it for me”, just trying to pretend you’re not saying just that.

It is just I learn by visual rather than text. For the simple reason is that if you are new to js then some of the terms go over my head. But I take on board your comments and i shall reread and repost with updated code. Many thanks

OK I have managed I think to create and array of the correct items. When I console.log the code:

info.forEach(function(data){console.log(data)});

it shows 2 entries which is the correct values…

when i click the #rowClk button which should console.log(item); it shows 2 items all same value. This button also opens the dialog and when the loop is run in the open: section, it shows 1 item.

I have posted updated code for your help. Many thanks

$(function() {
  info = [];
  $(document).on('click', '.rowChk', function() {
    $("input[type=checkbox]:checked").each(function() {
      currentRows = $(this).closest("tr");
      rackid = currentRows.find("td:eq(0)").html();
      rackservice = currentRows.find("td:eq(2)").html();
      rackactivity = currentRows.find("td:eq(3)").html();
      rackdept = currentRows.find("td:eq(4)").html();
      rackcompany = currentRows.find("td:eq(5)").html();
      rackaddress = currentRows.find("td:eq(6)").html();
      rackuser = currentRows.find("td:eq(7)").html();
      rackitem = currentRows.find("td:eq(8)").html();
      //rackboxsize = currentRows.find("td:eq(8)").html();
      rackddate = currentRows.find("td:eq(9)").html();
      rackdate = currentRows.find("td:eq(10)").html();
      info[0] = rackid;
      info[1] = rackservice;
      info[2] = rackactivity;
      info[3] = rackdept;
      info[4] = rackcompany;
      info[5] = rackaddress;
      info[6] = rackuser;
      info[7] = rackitem;
      info[8] = rackddate;
      info[9] = rackdate;
    });
    info.forEach(function(data) {
      console.log(data)
    });
    
    $(document).on('click', '#rowClk', function() {
      $.each(info, function(index, item) {
        $("#rack").dialog("open");
        $("#rack_id").val(info[0]);
        $("#rack_service").val(info[1]);
        $("#rack_activity").val(info[2]);
        $("#rack_dept").val(info[3]);
        $("#rack_company").val(info[4]);
        $("#rack_address").val(info[5]);
        $("#rack_user").val(info[6]);
        $("#rack_item").val(info[7]);
        //$("#rack_size").val(rackboxsize);
        $("#rack_datetimepicker").val(info[8]);
        $("#rack_ddatetimepicker").val(info[9]);
        console.log(item); // this shows 2 items all same value
      });
    });
  });
});
$(function() {
  $('#rack').dialog({
    autoOpen: false,
    title: 'New Intake Slot Assingment',
    height: 520,
    width: '50%',
    modal: true,
    resizable: false,
    position: {
      my: 'top',
      at: 'top+35'
    },
    open: function(event, ui) {
      $('#rack').css('overflow', 'hidden'); //this line does the actual hiding
      info.forEach(function(data) {
        //console.log(data);
      });
    },
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "blind",
      duration: 1500
    },
    buttons: [{
      text: "Submit",
      "class": 'defaultBtn',
      click: function(e) {
        e.preventDefault();
        var data = $('#rack').serialize();
        $.ajax({
          type: 'POST',
          url: '/lsorg/admin/niajax.php',
          data: data,
          beforeSend: function() {
            $(".text").show().html('Processing your request...');
          },
          success: function(data) {
            if (data.trim() == 'All fields must be completed') {
              $(".text").html('ERROR: You must complete all fields for the slot assignment.').css({
                "color": "red",
                "font-size": "13px",
                "margin-left": "21px"
              });
              return false;
            } else {
              $.get('/lsorg/admin/refreshActions.php?count=' + 'Actions', function(data) {
                //console.log(data);
                $(".actions").text(data);
              });
              $.get('/lsorg/admin/refreshActions.php?count=' + 'New Box Intake', function(data) {
                //console.log(data);
                $(".ni").text(data);
              });
              $("#rack").dialog("close");
              activity = 'New box Intake Assignment';
              showModelActionSuccess(data);
              $(".text").empty();
              $("#rack").trigger("reset");
              tableni.ajax.reload(null, false);
              return false;
            }
          },
          error: function(xhr) {
            $(".text").fadeIn(4000).html('Error occured.please try again').fadeOut(4000);
          },
          complete: function() {},
        })
      }
    }, {
      text: "Cancel",
      "class": 'defaultBtnClose',
      click: function() {
        $(this).dialog("close");
        $("#rack").trigger("reset");
        $(".text").empty();
      }
    }, ],
    close: function() {
      $("#rack").trigger("reset");
      $(".text").empty();
      $(".chosen-select").attr("data-placeholder", "Select a box size").val('').trigger('chosen:updated');
    }
  });
});

Okay, that’s a good starting point.

Lets focus on the creating of the array first; then we’ll handle what exactly you’re trying to do with it.

I like the selector, assuming of course there’s no other checkboxes on the page besides these ones. And we’re eaching them to pull the values. So you’ve got steps 1 and 2 down perfectly.

Now we need to slightly adjust info - specifically, we’re trying to make info a multidimensional array (or array of arrays).

Instead of info[1], info[2] etc, create a new array inside the loop; lets say we call it… row.
var row =
row[1] = rackservice;
row[2] = rackactivity;
etc etc etc.
When we get to the end, we then need to add this row to our info array.In array terms, that’s accomplished with a push. So we would say info.push(row)

Javascript multidimensional arrays operate the same way as any other array structure; they have a numeric index, and each index has a secondary index (or a third, fourth, etc, depending on how many ‘dimensions’ the array has.)

So, if we wanted the rackdept of the 3rd selected row, we could reference it as info[2][3] (indexes are 0-based, so the third item is actually in number 2).

If we forEach a multidimensional array, each iteration gives us the entire row of information.

info.forEach(function (i,row) {
  //now row[0] is this one's rackid, etc etc
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.