skip to Main Content

The following is an inline insert using HTML5 table data to a database table using jQuery and 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

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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.

    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.

    Any/All checkboxes that are ticked will appear in the POST array – any that remain unticked are ignored. The set method of the FormData api takes two parameters – a name and value pair. ( 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. The FormData object can be used with jQuery quite happily though I believe.

    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>

    network request showing checkboxes are present in request

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search