简体   繁体   English

使用 jQuery 和 AJAX 发送复选框数据和表格数据

[英]send checkbox data along with table data using jQuery and AJAX

The following is an inline insert using HTML5 table data to a database table using jQuery and AJAX.以下是使用 HTML5 表数据到使用 jQuery 和 AJAX 的数据库表的内联插入。 I would like to also send a checkbox data along with this table data, how can I achieve that?我还想连同这个表格数据一起发送一个复选框数据,我该如何实现呢?

<div id="add-product">
<div class="txt-heading">Add Product</div>
    <table cellpadding="10" cellspacing="1">
        <tbody>
            <tr>
                <th><strong>Name</strong></th>
                <th><strong>Code</strong></th>
                <th><strong>Description</strong></th>
                <th style="text-align:right;"><strong>Price</strong></th>
            </tr>   
            <tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
                <td contentEditable="true" data-id="product_name"></td>
                <td contentEditable="true" data-id="product_code"></td>
                <td contentEditable="true" data-id="product_desc"></td>
                <td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
            </tr>
        </tbody>
    </table>    
<div id="btnSaveAction">Save to Database</div>
</div>



<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$("#btnSaveAction").on("click",function(){
    params = ""
    $("td[contentEditable='true']").each(function(){
        if($(this).text() != "") {
            if(params != "") {
                params += "&";
            }
            params += $(this).data('id')+"="+$(this).text();
        }
    });
    if(params!="") {
        $.ajax({
            url: "insert-row.html",
            type: "POST",
            data:params,
            success: function(response){
              $("#ajax-response").append(response);
              $("td[contentEditable='true']").text("");
            }
        });
    }
});
</script>

code is from here代码来自这里

The solution may be this... If I understood correctly what you were asking.解决方案可能是这样的......如果我理解正确你的要求。

    <div id="add-product">
    <div class="txt-heading">Add Product</div>
        <table cellpadding="10" cellspacing="1">
            <tbody>
                <tr>
                    <th><strong>Name</strong></th>
                    <th><strong>Code</strong></th>
                    <th><strong>Description</strong></th>
                    <th style="text-align:right;"><strong>Price</strong></th>
                </tr>   
                <tr><form name="myform"><input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" /></form>
                    <td contentEditable="true" data-id="product_name"></td>
                    <td contentEditable="true" data-id="product_code"></td>
                    <td contentEditable="true" data-id="product_desc"></td>
                    <td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
                    <td><input type="checkbox" id="product_xxxx" name="product_xxxx" value="yes"></td>
                </tr>
            </tbody>
        </table>    
    <div id="btnSaveAction">Save to Database</div>
    </div>
    
    
    
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    $("#btnSaveAction").on("click",function(){
        params = ""
        $("td[contentEditable='true']").each(function(){
            if($(this).text() != "") {
                if(params != "") {
                    params += "&";
                }
                params += $(this).data('id')+"="+$(this).text();
            }
        });
    
        // For each checkbox whose name begins with 'product_'
        $("[type=checkbox][name^='product_']").each(function(){
            
            // If Checkbox Checked
            if($(this).prop('checked')) params += $(this).attr('id')+"="+$(this).val();

    
        });
        // End - For each checkbox whose name begins with 'product_'
    
    
        if(params!="") {
            $.ajax({
                url: "insert-row.html",
                type: "POST",
                data:params,
                success: function(response){
                  $("#ajax-response").append(response);
                  $("td[contentEditable='true']").text("");
                }
            });
        }
    });
    </script>

I mentioned using a FormData object to gather together all the data that you want to send so the following is an example using vanilla Javasript that does just that.我提到使用FormData object 来收集您要发送的所有数据,因此以下是一个使用 vanilla Javasript 的示例。

The form must be either entirely within a single table-cell or the entire table must be wholly contained within the form for the markup to be valid - hence the form below, with several checkboxes to illustrate the point, contains the table with the contentEditable cells. form必须完全位于单个表格单元格中,或者整个表格必须完全包含在表格中以使标记有效 - 因此,下面的表格带有几个复选框来说明这一点,包含带有contentEditable单元格的表格.

Any/All checkboxes that are ticked will appear in the POST array - any that remain unticked are ignored.任何/所有勾选的复选框都将出现在 POST 数组中 - 任何未勾选的都将被忽略。 The set method of the FormData api takes two parameters - a name and value pair. FormData api 的set方法采用两个参数 - 名称和值对。 ( a third value is possible if you wish to supply a filename, for an upload for instance ) (如果您希望提供文件名,则可以使用第三个值,例如上传)

I appreciate that the question says jQuery but my efforts with that resulted in errors that I knew not how to resolve - hence vanilla JS.我很欣赏这个问题说 jQuery 但我的努力导致了我不知道如何解决的错误 - 因此是香草 JS。 The FormData object can be used with jQuery quite happily though I believe.尽管我相信, FormData object 可以非常愉快地与 jQuery 一起使用。

 const d=document; d.querySelector('button[name="save"]').addEventListener('click', e=>{ // create the FormData object bound to the `form` let fd = new FormData( document.forms.myform ); let col=d.querySelectorAll('td[contentEditable="true"]'); // add all the contentEditable text to the FormData object col.forEach(n=>fd.set(n.dataset.id, n.textContent)); // send the http request fetch('insert-row.html', { method:'post', body:fd }).then( r=>r.text() ).then( text=>{ d.getElementById('ajax-response').insertAdjacentHTML('beforeend',text); col.forEach(n=>n.textContent='') }).catch(e=>console.log(e)) });
 body,body *{ font-family:monospace; font-size:1rem } table{ width:90%; border:1px solid grey; margin:1rem; } tr th:nth-of-type(4), tr td[contentEditable='true']:nth-of-type(4){ text-align:right; } tr,td{margin:0.1rem;} td,th{ padding:0.25rem; border:1px solid grey } [contentEditable]:focus{background:rgba(0,255,0,0.25)}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="add-product"> <div class="txt-heading">Add Product</div> <form name="myform"> <input type="checkbox" name="myCheckboxes[]" value="someValue - 1" />1 <input type="checkbox" name="myCheckboxes[]" value="someValue - 2" />2 <input type="checkbox" name="myCheckboxes[]" value="someValue - 3" />3 <input type="checkbox" name="myCheckboxes[]" value="someValue - 4" />4 <input type="checkbox" name="myCheckboxes[]" value="someValue - 5" />5 <input type="checkbox" name="myCheckboxes[]" value="someValue - 6" />6 <table cellpadding="10" cellspacing="1"> <tbody> <tr> <th><strong>Name</strong></th> <th><strong>Code</strong></th> <th><strong>Description</strong></th> <th><strong>Price</strong></th> </tr> <tr> <td contentEditable="true" data-id="product_name"></td> <td contentEditable="true" data-id="product_code"></td> <td contentEditable="true" data-id="product_desc"></td> <td contentEditable="true" data-id="product_price"></td> </tr> </tbody> </table> </form> <button name='save' type='button'>Save to Database</button> </div> <div id='ajax-response'></div>


请求中存在显示复选框的网络请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM