使用jquery在表中单击编辑后如何为每个字段添加输入?

时间:2017-06-23 01:24:59

标签: jquery html knockout.js

我想知道在使用jquery按下编辑后如何向表中的每个字段添加输入。所以基本上我在表格中有7个列有7个标题用于html,我希望能够在按下编辑按钮后编辑每个字段,编辑按钮位于表格右侧的每一行。在我为该特定行的每列添加输入字段后,一旦输入进入,我想使用ajax调用我的更新api。这是我的HTML代码。

<div id="table-wrapper"> 
    <div id="table-scroll">
    <table id="results" class="hidden" cellspacing=10px>
        <thead>
            <tr class = "spacing">
                <th>SAM ID</th>
                <th>Item Description</th>
                <th>Issued QTY</th>
                <th>Opening QTY</th>
                <th>Closing QTY</th>
                <th>Corrupted QTY</th>
                <th>Remarks</th>
            </tr>
        </thead>
        <tbody id="bResults">
        </tbody>
    </table>
    </div>
    </div>

这是我的js代码连接到html。

function search(){

var samId = $('#samId').val();
var postData = { "samId": samId };
var postJSON = JSON.stringify(postData);
$.ajax({
    url: "http://localhost:3000/api/queryRecord", // server url
    type: "POST", //POST or GET
    contentType: "application/json",
    data: postJSON, // data to send in ajax format or querystring format
    dataType : "JSON", //dataType is you telling jQuery what kind of 
    response to expect
    success: function(response) {
        alert('success');
         if(response){
            var len = response.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    if(response[i].samID && response[i].itemDescription){
                        txt += "<tr class='rowdata'><td>"+response[i].samID 
                        +"</td><td>"+response[i].itemDescription+"</td><td>"
                        +response[i].issuedQTY + "</td>
                        <td>"+response[i].openingQTY + "</td>
                        <td>"+response[i].closingQTY
                        +"</td><td>"+response[i].corruptedQTY+"</td>
                        <td>"+response[i].Remarks+"</td><td>" 
                        + "<input class='button-edit' type='submit' 
                        value='Edit' onclick = 'edit()' />" 
                        +"</td></tr>";
                    }
                }

                $("#bResults").empty();
                if(txt != ""){
                    $("#results").removeClass("hidden");
                    $("#bResults").append(txt);
                }
            }
        }
    },
    error: function(response) {
        alert('error');
    }
});
event.preventDefault();
}

 function edit(){
 var currentTD = $(this).parents('tr').find('td');
      if ($(this).html() == 'Edit') {                  
          $.each(currentTD, function () {
              $(this).prop('contenteditable', true)
          });
      } else {
         $.each(currentTD, function () {
              $(this).prop('contenteditable', false)
          });
      }

      $(this).html($(this).html() == 'Edit' ? 'Save' : 'Edit')
}

我的search()工作正常但只是想表明我的回复是如何编码的。这个edit()基本上是我的,但由于没有关于编辑和添加输入的方法的任何线索,因此代码来自另一个问题Making row editable when hit row edit button我真的不知道如何使用人们在该特定行中编辑的字段。我也使用mongodb作为数据库。请以更简单的方式解释它,让我更好地理解。谢谢!

更新 根据Mohamed-Yousef的说法

function search(){

var samId = $('#samId').val();
var postData = { "samId": samId };
var postJSON = JSON.stringify(postData);
$.ajax({
    url: "http://localhost:3000/api/queryRecord", // server url
    type: "POST", //POST or GET
    contentType: "application/json",
    data: postJSON, // data to send in ajax format or querystring format
    dataType : "JSON", //dataType is you telling jQuery what kind of 
    response to expect
    success: function(response) {
        alert('success');
         if(response){
            var len = response.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    if(response[i].samID && response[i].itemDescription){
                        txt +="<tr class='rowdata'><td>"+response[i].samID+ 
                              "</td>"+<td>"+response[i].itemDescription+
                               "</td>"+"<td>"+response[i].issuedQTY + 
                               "</td>"+"<td>"+response[i].openingQTY + 
                               "</td>"+"<td>"+response[i].closingQTY+
                               "</td>"+"<td>"+response[i].corruptedQTY+
                               "</td>"+"<td>"+response[i].Remarks+"</td>"
                               +"<td><input class='button-edit' 
                               type='submit' value='Edit' onclick = 'edit()' 
                               /></td>"+"</tr>";
                    }
                }

                $("#bResults").empty();
                if(txt !== ""){
                    $("#results").removeClass("hidden");
                    $("#bResults").append(txt);
                }
            }
        }
    },
    error: function(response) {
        alert('error');
    }
});
event.preventDefault();
}
 function edit(el){
 var currentTD = $(el).closest('tr').find('td').not($(el).closest('td'));
      if ($(this).html() == 'Edit') {                  
          $.each(currentTD, function () {
              $(this).prop('contenteditable', true)
          });
      } else {
         $.each(currentTD, function () {
              $(this).prop('contenteditable', false)
          });
      }

      $(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit')
}

似乎无法正常工作,但仍然会出现错误Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined

根据Bryan Dellinger所做的另一个答案是使用knockout.js

<table id="results" class="hidden" cellspacing=10px>
        <thead>
            <tr class = "spacing">
                <th>SAM ID</th>
                <th>Item Description</th>
                <th>Issued QTY</th>
                <th>Opening QTY</th>
                <th>Closing QTY</th>
                <th>Corrupted QTY</th>
                <th>Remarks</th>
            </tr>
        </thead>

             <tbody id="bResults" data-bind="foreach: txt">
        <tr>
            <td>
   <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: samID">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: samID"></span>
   <!-- /ko -->
            </td>
        <td>
   <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: itemDescription">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: itemDescription"></span>
   <!-- /ko -->
        </td>
        <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: issuedQTY">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: issuedQTY"></span>
   <!-- /ko -->
        </td>
        <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: openingQTY">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: openingQTY"></span>
   <!-- /ko -->
        </td>
        <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: closingQTY">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: closingQTY"></span>
   <!-- /ko -->
        </td>
        <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: corruptedQTY">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: corruptedQTY"></span>
   <!-- /ko -->
        </td>
        <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: corruptedQTY">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: corruptedQTY"></span>
   <!-- /ko -->
        </td>
                    <td>
    <!-- ko if: buttonText() === 'Save' -->
            <input data-bind="textInput: Remarks">
   <!-- /ko -->
       <!-- ko if: buttonText() === 'Edit' -->
            <span data-bind="text: Remarks"></span>
   <!-- /ko -->
        </td>
        <td><button data-bind="text: buttonText, click: $parent.click">
        </button></td>
        </tr>
        </tbody>
    </table>
  <script src="js/jquery-3.2.1.min.js"></script>
  <script src="js/mainpage.js"></script>
  <script 
  src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-
   min.js"></script> 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1
  /knockout.mapping.min.js"></script>  

这是js

function search(){

var samId = $('#samId').val();
var postData = { "samId": samId };
var postJSON = JSON.stringify(postData);
$.ajax({
    url: "http://localhost:3000/api/queryRecord", // server url
    type: "POST", //POST or GET
    contentType: "application/json",
    data: postJSON, // data to send in ajax format or querystring format
    dataType : "JSON", //dataType is you telling jQuery what kind of response to expect
    success: function(response) {
        alert('success');
         if(response){
            var len = response.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    if(response[i].samID && response[i].itemDescription){
                        txt = [{
                                "samID": response[i].samID,
                              "itemDescription":response[i].itemDescription,
                               "issuedQTY": response[i].issuedQTY,
                                "openingQTY": response[i].openingQTY,
                                "closingQTY": response[i].closingQTY,
                                "corruptedQTY": response[i].corruptedQTY,
                                "editMode" : false,
                                "Remarks": response[i].Remarks,
                                "buttonText": "Edit"
                        }]
                    }
                }

                $("#bResults").empty();
                if(txt != ""){
                    $("#results").removeClass("hidden");
                    $("#bResults").append(txt);
                }
            }
        }
    },
    error: function(response) {
        alert('error');
    }
});
event.preventDefault();
}

1 个答案:

答案 0 :(得分:1)

我认为问题是:在您的$(this)函数中使用edit(),它引用了对象我不知道窗口或其他什么但它不是编辑按钮..所以你可以传递edit(element)作为参数和html使用onclick="edit(this)"

使用input时..使用.val()代替.html()

要避免编辑输入的td,您可以使用.not()

所以你的代码应该是

function edit(el){
 var currentTD = $(el).closest('tr').find('td').not($(el).closest('td')); // tds except the td which closest to the edit button
 if ($(el).val() == 'Edit') {                  
     $.each(currentTD, function () {
       $(this).prop('contenteditable', true)
     });
  } else {
     $.each(currentTD, function () {
       $(this).prop('contenteditable', false)
     });
  }

  $(el).val($(el).val() == 'Edit' ? 'Save' : 'Edit')
}

在html 上使用type =“button”无需使用submit

<input class='button-edit' type='button'  value='Edit' onclick = 'edit(this)' /> 
//--------------------------------^-------------------------------------^--------

行HTML结构应该像

txt += "<tr class='rowdata'><td>"+response[i].samID+"</td>"
  +"<td>"+response[i].itemDescription+"</td>"
  +"<td>"+response[i].issuedQTY + "</td>"
  +"<td>"+response[i].openingQTY + "</td>"
  +"<td>"+response[i].closingQTY+"</td>"
  +"<td>"+response[i].corruptedQTY+"</td>"
  +"<td>"+response[i].Remarks+"</td>"
  +"<td><input class='button-edit' type='submit' value='Edit' onclick = 'edit()' /></td>" 
  +"</tr>";

!==

中使用!=代替if(txt != ""){