2014-09-23 41 views
1

我有一個使用javascript和ajax動態生成的tablesorter表。有用戶輸入來更改值,當他們單擊按鈕轉到下一個或上一個記錄時,它需要將表中的信息保存到MySQL表中。我查看了這裏的許多帖子並嘗試了大量示例,但仍無法獲取表中的任何數據以發佈到我的PHP頁面以保存它。
這裏是我的表的第一行的一個示例:從javascriptort表中提取數據使用javascript

$("#guides").append('<tr><td id="amCodeOld">'+data.amCodeOld+'</td><td><input type="text" class="qty" id="amOldQty"/></td><td>'+data.amOldPrice+ 
              '</td><td>'+data.am+ 
              '</td><td>'+data.amCodeNew+'</td><td><input type="text" class="qty" id="amNewQty"/></td><td>'+data.amNewPrice+ 
              '</td><td><input type="checkbox" id="amS" '+ 
              '"/></td><td><input type="checkbox" id="amR"'+'"/></td><td><input type="checkbox" id="amCall"'+ 
              '"/></td><td><input type="text" id="amComm" value="'+ 
              '"/></td></tr>'); 

有更多像這樣的,每次我使用的是不同的引導排。我需要找到的是具有amOldQty,amNewQty等ID以及不同複選框的輸入的值。 我有Next,Prev和Print按鈕,當按鈕被點擊時,我試圖調用一個名爲save()的函數來獲取信息,並通過ajax將它發送到另一個PHP頁面進行保存。
保存()看起來是這樣的:

function save() { 
var amOldQty 
$('#guides tr').each(function(){ 
alert("searching "); 
     amOldQty= $(this).find('#amOldQty').val(); 
     if (amOldQty=='' || amOldQty== null) { 
     amOldQty = "Not Showing Number"; 
     } 
    console.log(amOldQty); 
});// END OF EACH FUNCTION 

我曾嘗試:

var amOldQty; 
$('#guides tbody tr').each(function() { 
     amOldQty = $(this).find('td:nth-child(1) input').val(); 
    }); 
console.log(amOldQty); 

和日誌顯示不明確的。我也嘗試過使用更直接的方法

$('#guides tbody tr').each(function() { 
     amOldQty = $(this).find('#amOldQty').val(); 
    }); 

而且還是什麼都沒有。我收到了搜索警報,但在console.log(amQtyOld)中顯示的所有內容都是「不顯示數字」。我甚至試圖在第一次創建表時填充輸入,但它仍然沒有找到該數字。
更新如果我添加的TD:

$(guides tr td).each(function(){... 

,它甚至沒有給我的「搜索」的警報。 如何從此表中獲取所有數據,以便我可以保存它?似乎我所嘗試的一切都應該起作用。

回答

0

最終的答案似乎是硬編碼輸入$(「#amOldQty :)。val()的值並將它們作爲數據通過ajax傳遞給我的php文件以保存信息。以下是完成的代碼如果任何人有一個類似的問題:

function save() { 

function GuidesSave(){ 
this.update(); 
} 

GuidesSave.prototype.list = ['am','fol','tich','book','neb','ster','c','byte','ing']; 

GuidesSave.prototype.update = function(){ 
for(var i = 0 ; i < this.list.length ; i++){ 
var guide = this.list[i]; 
this[ guide + 'S' ] = $("#" + guide+'S').is(":checked") ? 1 : 0; 
this[ guide + 'R' ] = $("#" + guide+'R').is(":checked") ? 1 : 0; 
this[ guide + 'Call' ] = $("#" + guide+'Call').is(":checked") ? 1 : 0; 
}// end of for loop 
} 
var guides = new GuidesSave(); 

$.ajax({ 
    type: "POST", 
     url: "poSave.php", 
     dataType: "json", 
     data: ({po: $('#po').val(),isbn:$("#isbn13").val(),amOldQty:$("#amOldQty").val(),amNewQty:$("#amNewQty").val(),amS:guides.amS,amR:guides.amR, amCall:guides.amCall,amComm:$("#amComm").val(), 
      folOldQty:$("#folOldQty").val(),folNewQty:$("#folNewQty").val(),folS:guides.folS,folR:guides.folR, folCall:guides.folCall,folComm:$("#folComm").val(), 
      tichOldQty:$("#tichOldQty").val(),tichNewQty:$("#tichNewQty").val(),tichS:guides.tichS,tichR:guides.tichR, tichCall:guides.tichCall,tichComm:$("#tichComm").val(), 
      bookOldQty:$("#bookOldQty").val(),bookNewQty:$("#bookNewQty").val(),bookS:guides.bookS,bookR:guides.bookR, bookCall:guides.bookCall,bookComm:$("#bookComm").val(), 
      nebOldQty:$("#nebOldQty").val(),nebNewQty:$("#nebNewQty").val(),nebS:guides.nebS,nebR:guides.nebR, nebCall:guides.nebCall,nebComm:$("#nebComm").val(), 
      sterOldQty:$("#sterOldQty").val(),sterNewQty:$("#sterNewQty").val(),sterS:guides.sterS,sterR:guides.sterR, sterCall:guides.sterCall,sterComm:$("#sterComm").val(), 
      cheggOldQty:$("#cOldQty").val(),cheggNewQty:$("#cNewQty").val(),cheggS:guides.cS,cheggR:guides.cR, cheggCall:guides.cCall,cheggComm:$("#cComm").val(), 
      byteOldQty:$("#byteOldQty").val(),byteNewQty:$("#byteNewQty").val(),byteS:guides.byteS,byteR:guides.byteR, byteCall:guides.byteCall,byteComm:$("#byteComm").val(), 
      ingOldQty:$("#ingOldQty").val(),ingNewQty:$("#ingNewQty").val(),ingS:guides.ingS,ingR:guides.ingR, ingCall:guides.ingCall,ingComm:$("#ingComm").val(), 
      qty1: $('#topqty').val(),price1: $('#topVal').html(),comp1:$('#topCo').html(), 
      qty2: $('#secqty').val(),price2: $('#secVal').html(),comp2: $('#secCo').html(), 
      qty3: $('#thrqty').val(),price3: $('#thrVal').html(),comp3: $('#thrCo').html()}), 
     success: function(data){ 
     } 
}); 
}// END OF SAVE FUNCTION 

的GuideSave功能通過所有複選框環路(27分不同的人),看看whichones檢查,所以我可以將它們保存爲爲1或0,然後讓他們檢查或者當記錄被召回的時候沒有。

0

如果您的用戶使用browsers that support contenteditable elements,那麼您可以查看contenteditable widget我可用於我的fork of tablesorter

如果你不想使用CONTENTEDITABLE元素,那麼你可以嘗試下面的代碼(複製並從CONTENTEDITABLE演示修改,但沒有測試)

var $table = $('table'); 

$table.children('tbody').on('change', 'input', function(event){ 
    var $input = $(this), 
    $cell = $input.closest('td'), 

    newContent = $input.val(), 
    cellIndex = $cell[0].cellIndex, // there shouldn't be any colspans in the tbody 
    rowIndex = $this.closest('tr').attr('id'); // unique row id 

    // update tablesorter 
    $table.trigger("updateCell", [$cell]); 

    $.post("mysite.php", { 
    "row"  : rowIndex, 
    "cell" : cellIndex, 
    "content" : newContent 
    }); 

}); 

希望,你也使用該列的input parser

+0

這看起來好像是如果我想保存信息每隔一段時間更新一個單元格,但是有很多單元格可以是c掛起,所以我試圖保存一次,當他們點擊下一個,prev,或打印按鈕。 – Jim 2014-09-24 13:36:13

0

你真的不清楚你想要呈現數據的方式或方式。然而,here is a JSFiddle,它看起來你的願望。

函數createRowsForTesting()只是創建表中的行並填充<input>字段以使測試更容易。

getDataFromTable()走一個<表>,或所有<表>的行,送你說你想在控制檯中的數據的功能。從你自己對這個問題的回答可以清楚地看到,你真的想訪問更多的<輸入>元素比你的問題中提到的要多。因此,這個函數現在構建一個包含<輸入>字段中數據的鍵:值對的對象數組。數組中有一個對象用於每一行。數組返回給調用函數。

wrapGetDataFromTable()包裝getDataFromTable()提供的表ID,我們僅在<TBODY>標籤內尋找行,而我們要輸出到控制檯的功能。輸出由getDataFromTable()返回的數組,因此我們可以看到數據結構。每次按[打印到控制檯]按鈕時,該功能都會設置爲運行。

對於表看起來像(具有標題行): Test table

的輸出是:

amOldQty=amOldQty0_text amNewQty=amNewQty0_text amS=on amR=off amCall=off amComm=amComm0_text 
amOldQty=amOldQty1_text amNewQty=amNewQty1_text amS=off amR=on amCall=off amComm=amComm1_text 
amOldQty=amOldQty2_text amNewQty=amNewQty2_text amS=off amR=off amCall=on amComm=amComm2_text 

The array of row input data objects is: 
[0] Object { amOldQty="amOldQty0_text", amNewQty="amNewQty0_text", amS="on", more...} 
     amOldQty: "amOldQty0_text" 
     amNewQty: "amNewQty0_text" 
     amS:  "on" 
     amR:  "off" 
     amCall:  "off" 
     amComm:  "amComm0_text" 

[1] Object { amOldQty="amOldQty1_text", amNewQty="amNewQty1_text", amS="off", more...} 
     amOldQty: "amOldQty1_text" 
     amNewQty: "amNewQty1_text" 
     amS:  "off" 
     amR:  "on" 
     amCall:  "off" 
     amComm:  "amComm1_text" 

[2] Object { amOldQty="amOldQty2_text", amNewQty="amNewQty2_text", amS="off", more...} 
     amOldQty: "amOldQty2_text" 
     amNewQty: "amNewQty2_text" 
     amS:  "off" 
     amR:  "off" 
     amCall:  "on" 
     amComm:  "amComm2_text" 

JavaScript的:

/** 
* Runs through a table getting the values from <input> fields. 
* It only looks in the <tbody>, not the <thead> 
* @param tableId 
*   The DOM ID of the table from which we desire to obtain the 
*   input values. 
*   If tableId is not a string, then look in all table rows in all tables. 
* @param keyAttr 
*   The attribute of the <input> which contains the value which will 
*   be used as the key for the key:value pair within the Object returned. 
*   This needs to be a value which is unique, wihin the table row. 
*   A normal use would be "id". 
*   If a value is duplicated a message is sent to the console and only 
*   the last value is kept. 
*   The default is "id". 
* @param justBody 
*   If true, look only within the <tbody> tag, not any other part of 
*   the table (e.g. <thead>). 
*   The default is true. 
* @param includeBlank 
*   Boolean indicating if the returned array should contain an entry for 
*   rows which are found to be blank. 
*   The default is true. 
* @param consoleOutput 
*   Send a line to the console with the key:value pairs separated by 
*   tabs for each row. 
*   The default is false. 
* @return Object 
*   Returns an Array of Objects with key:value pairs for the rows. 
*   If there were no <input> 
* Copyright 2014 by Makyen. 
* Released under the MPL 2.0. http://mozilla.org/MPL/2.0/. 
*/ 
function getDataFromTable(tableId, keyAttr, justBody, includeBlank, consoleOutput) { 
    //This assumes that within the row each input has a unique attribute keyAttr. 
    //Set defaults: 
    var tableSelector = (typeof tableId === "string") ? "#" + tableId : "table"; 
    keyAttr = (typeof keyAttr === "string") ? keyAttr : "id"; 
    includeBlank = (typeof includeBlank === "boolean") ? includeBlank : true; 
    justBody = (typeof justBody === "boolean") ? justBody : true; 
    consoleOutput = (typeof consoleOutput === "boolean") ? consoleOutput : false; 

    var bodySelector = (justBody) ? " tbody" : ""; 
    var toReturn = []; 
    var selector = tableSelector + bodySelector + ' tr'; 
    $(selector).each(function() { 
     var inputs = {}; 
     $(this).find('input').each(function() { 
      //Get the value for all inputs on this line. 
      var attrValue = $(this).attr(keyAttr); 
      if (typeof inputs[attrValue] !== "undefined") { 
       console.log("Warning: When attempting to get data from the table id=" // 
          + tableId + " the value of the key attribute, " + keyAttr // 
          + ", was not unique for value=" + attrValue); 
      } 
      //Get the value of the <input>. 
      if ($(this).is(':checkbox')) { 
       //Special case the checkboxes because .val() does not return 
       //the correct informaiton for them. 
       //First indicate that all checkboxes are off. 
       inputs[attrValue] = "off"; 
       //Specifically determine if the current one is checked. 
       if ($(this).is(':checked')) { 
        inputs[attrValue] = "on"; 
       } 
      } else { 
       //Add this input to the object 
       inputs[attrValue] = $(this).val(); 
      } 
     }); 
     var inputKeys = Object.keys(inputs); 
     if (inputKeys.length > 0) { 
      //There were <input> tags on this row. 
      var outputText = ""; 
      if (consoleOutput) { 
       inputKeys.forEach(function (value) { 
        outputText += value + "=" + inputs[value] + "\t"; 
       }); 
       console.log(outputText); 
      } 
      toReturn.push(inputs); 
     } else { 
      //No <input> tags on this row 
      if (includeBlank) { 
       if (consoleOutput) { 
        console.log("A row without <input> tags was found."); 
       } 
       toReturn.push(inputs); 
      } 
     } 
    }); 
    return toReturn; 
} 

function wrapGetDataFromTable() { 
    //This wraper is so the getDataFromTable() function remains 
    // generic. The wrapper merely defines which table from which to 
    // get the data, 
    // the attribute to use for unique keys = "id" 
    // to look only in the <tbody> 
    // to not include an object for the lines which are blank 
    // and output the row data to the console. 
    var toReturn = getDataFromTable("guides", "id", true, false, true); 
    if (typeof console.dir === "function") { 
     //Make sure console.dir() exists prior to using it. 
     console.log("The array of row input data objects is:"); 
     console.dir(toReturn); //Let us see the Object in the console for checking. 
    } 
    return toReturn; 
} 
$('#to-console-button').click(wrapGetDataFromTable); 


//The rest is setup for creating the table header and rows. 
//It is only for testing. 

function createRowsForTesting() { 
    const numRowsToCreate = 3; 

    var i; 
    var data = { 
     amCodeOld: "amCodeOld", 
     amOldPrice: "amOldPrice", 
     am: "am", 
     amCodeNew: "amCodeNew", 
     amNewPrice: "amNewPrice" 
    }; 

    //Create the table 
    //First add a header. 
    $("#guides thead").append('<tr><th>amCodeOld_H</th>' // 
           + '<th>amOldQty_H</th>' // 
           + '<th>amOldPrice_H</th>' // 
           + '<th>am_H</th>'   // 
           + '<th>amCodeNew_H</th>' // 
           + '<th>amNewQty_H</th>' // 
           + '<th>amNewPrice_H</th>' // 
           + '<th>amS_H</th>'   // 
           + '<th>amR_H</th>'   // 
           + '<th>amCall_H</th>'  // 
           + '<th>amComm_H</th></tr>'); 
    //Now the body rows. 
    for (i = 0; i < numRowsToCreate; i++) { 
     //From stackoverflow question: http://stackoverflow.com/questions/25998929/extract-data-from-a-tablesorter-table-with-javascript 
     $("#guides tbody").append('<tr><td id="amCodeOld">'+data.amCodeOld+'</td><td><input type="text" class="qty" id="amOldQty"/></td><td>'+data.amOldPrice+ // 
              '</td><td>'+data.am+ // 
              '</td><td>'+data.amCodeNew+'</td><td><input type="text" class="qty" id="amNewQty"/></td><td>'+data.amNewPrice+ // 
              '</td><td><input type="checkbox" id="amS" '+ // 
              '"/></td><td><input type="checkbox" id="amR"'+'"/></td><td><input type="checkbox" id="amCall"'+ // 
              '"/></td><td><input type="text" id="amComm" value="'+ // 
              '"/></td></tr>'); 
    } 
    //* 
    //Fake having the table filled in, as I am tired of entering the input 
    //You have to try it without this, but with manual input in order to truly verify 
    var row = 0; 
    $('#guides tbody tr').each(function() { 
     $(this).find('#amOldQty').val("amOldQty" + row + "_text"); 
     $(this).find('#amNewQty').val("amNewQty" + row + "_text"); 
     $(this).find('#amComm').val("amComm" + row + "_text"); 
     row++; 
    }); 
    //*/ 
} 



createRowsForTesting(); 

HTML:

<table class="tablesorter" id="guides"> 
    <thead></thead> 
    <tbody></tbody> 
</table> 
<button type="button" id="to-console-button">print to console</button> 
<!-- values to use to fill input: 
amOldQty0_text 
amOldQty1_text 
amNewQty0_text 
amNewQty1_text 
amComm0_text 
amComm1_text --> 

注意:行中使用的選擇器($("#guides").append('<tr>...)將錶行添加到表中可能是您​​的問題。它目前將行添加爲<table>中的最後一個元素,而不是<tbody>中的最後一個元素。雖然瀏覽器應該對此進行補償,但在您的環境中它可能不會這樣做。嘗試$("#guides tbody").append('<tr>...

但是,該問題更可能是<tbody>中的標題行(或沒有輸入單元格的行)。該代碼現在說明了這種可能性。

+0

嗨Makyen,感謝您付出這麼多時間,但是,當我嘗試您的建議時,我得到了undefined amOldQty和關閉3個複選框。我精確地複製了你的printToConsole函數,並手動輸入一個數字到amOldQty框中。 – Jim 2014-09-29 11:42:33

+0

請參閱更新。 – Jim 2014-09-29 13:22:22

+0

更新了其他兩個輸入。表創建代碼中存在一個錯誤,而不是打印.--好的。鑑於你在你身邊看到問題,但我沒有看到任何問題,我們需要找出差異。你是否在[JSFiddle](http://jsfiddle.net/h2Lq7wa9/11/)或你自己的代碼中看到了undefined/off問題?如果你還沒有試過JSFiddle,或者它沒有爲你工作,請再試一次。你使用的是什麼操作系統和瀏覽器?什麼版本的jQuery/tablesorter?你使用的是什麼附件?什麼是*精確*調用tablesorter設置排序? – Makyen 2014-09-29 15:20:34