On change of quantity I am calling jquery ajax as shown below. I am problem when at bottom of the

On change of quantity I am calling jquery ajax as shown below. I am problem when at bottom of the

ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

Link to test case:
Debugger code (debug.datatables.net):
Error messages shown:
Description of problem:

Answers

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0
    edited August 2022

    When I am at the bottom of the page and when I change the quantity & moves to next quantity in next row with mouse click my page moves to the top of the page. How to keep my cursor on that quantity textbox clicked and how to keep page from scrolling to top?
    below is the code.

    // quantity call ajax and returns calculated values.
    
    $(document).on('change', '#quantity', function(){
       
    
       // ('quantity').focus();
      // table.cell( ':eq(0)' ).focus();
        var quantity = $(this).val();
        var qtyproid = $(this).attr("name");  
        var operation ='qtyedit';
        var OrderType  ='Regular'; //Clearance
    
        if( quantity != '' ) 
        {
            // alert("quantity" + Qty);
            $.ajax({
                url:"upsert.php",
                method:'POST',
                data:{qtyproid:qtyproid,quantity:quantity,operation:operation,OrderType:OrderType},
                dataType: 'json',
                success:function(data)
                {
                    var shoping =  '<sup>'  + data['data'][0] + '</sup>';
                    $("#cartcount").html(shoping);
                    $("#ftotalQty").text(data['data'][8]);
                    $("#ftotalAmt").text(data['data'][9]);
                    $("#fafterdistotalAmt").text(data['data'][10]);
                   
                    var oTable = $('#product_table').DataTable();
                    oTable.ajax.reload( null, false ); 
                    return false;
    
    
                }
            });
        }
        else
        {
            alert("Please enter quantity");
        }
         
    });
    
    column quantity is set 
    
        $sub_array[] = $price;
    
        $sub_array[] = //$row['Qty'];
       '              
        <div id="inputdiv" class="input-group">
            <span class="input-group-btn">
                <button type="button" class="quantity-right-plus btn btn-success btn-number" name="'. $row['Id'] .'" data-type="plus" data-field="">
                    <span class="glyphicon glyphicon-plus"></span>
                </button>
            </span>
                <input type="text" id="quantity" name="'. $row['Id'] .'" class="myTextBoxes" value="'.  $row["Qty"] . '"maxlength="5" size="2" "min="0" max="1000">
            <span class="input-group-btn">
                <button type="button" class="quantity-left-minus btn btn-danger btn-number" name="'. $row['Id'] .'" data-type="minus" data-field="">
                    <span class="glyphicon glyphicon-minus"></span>
                </button>
            </span>
        </div>
    
    

    Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    Its difficult to visualize what is happening with your code snippets. Please provide a link to your page or a test case replicating the issue so we can try out your solution to offer suggestions.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

    Problem is when datatable Qty column textbox on change event is called when we click on next qty textbox. In on change event it calls dt.ajax.reload( null, false ) and cursor which was highlighting on second row disappears. Same things happen when user is at bottom of the page then not only focus on qty column is lost but also the page scrolls to top. User needs find on which row is was working on..

    I tried to fix this by calling below line in on change event

    $(this).find("td:eq(7) input[type='text']").focus();

    but it is not working.

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    In on change event it calls dt.ajax.reload( null, false ) and cursor which was highlighting on second row disappears.

    Sounds like you will need to determine which text box has focus and in the ajax.reload() callback function set the focus back to that input.

    when user is at bottom of the page then not only focus on qty column is lost but also the page scrolls to top

    Maybe the problem is that you have multiple ID's that are the same:

    <input type="text" id="quantity"
    

    I'm assuming this input is in each row. ID's are to be unique on the page. Maybe fixing this will help. Take a look at this delegated events example for the best practice way to create events.

    Kevin

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

    No it not because of <input type="text" id="quantity'. $row['Id'] .'"
    Now textbox id is unique. But error still remains.

    can i call something like below and send row number to it to set focus.

    table = $('#example').DataTable(); table.ajax.reload( function ( json ) {    $(
    //setfocus();
    $(row[7]).find("td:eq(7) input[type='text']").focus();
    } );

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    row[7] in the callback function is likely undefined and so won't work. You can use row().node() to get the node of the desired row.

    Now textbox id is unique. But error still remains.

    Sorry I assumed that lines 50-62 were the row inputs you show in you screenshot. To avoid confusion please provide a test case showing the issues you are having. You can use one of the JS BIN Ajax examples here for the ajax.reload().

    Kevin

  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    Sounds like you might be using PHP to output an event listener combo for every input? What I'd do is add a delegated event listener (as Kevin mentioned) for each plus icon and each minus icon (which you can do with CSS selectors), then get the parent element of the icon, and inside that parent, find the input. Then increment or decrement the found value as needed.

    Thus you have a reusable component.

    The extra step would be to just have your PHP output the input element, and then loop over each input adding the +/- icons for each with Javascript. That could then be used anywhere you need on your site.

    Allan

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

    Thanks Allan and Kevin.

    see my code below. I now kept textbox only to show what problem I am facing.

    Only problem is onchange event ajax perform some calculation and then reloads the datatable. Then my page scroll to top and my focus or cursor from textbox that I last clicked is lost.

    On this jquery function i am facing problem
    $(document).on('change', '.myTextBoxes', function(e){)

    I will try to use JS BIN examples laer.

    please find the code below.

    $(document).ready(function(){

    load_data();
    
    function load_data()
    { 
    
        var dataTable = $('#product_table').DataTable({
    
            "responsive": true,
    
            "serverSide":true,
            "pagingType": "simple_numbers",
            "pageLength": 20,
            "lengthMenu": [20, 40, 150,200],        
            "columnDefs":[],   
            "ajax" : {
                url:"fetchtest.php",
                method : "POST",
            },
    
                //-
        }); //dATAVARDEFINE
            //================
        //================
    
    } //loaddata //////////////////////////////////////
    

    }); //DOCREADY//////////////
    /////////////////

    //qtyupdate change
    $(document).on('change', '.myTextBoxes', function(e){

    var quantity = $(this).val();
    var qtyproid = $(this).attr("name");  
    var operation ='qtyedit';
    var OrderType  ='Regular'; //Clearance
    
    if( quantity != '' ) 
    {
        // alert("quantity" + Qty);
        $.ajax({
            url:"upsert.php",
            method:'POST',
            data:{qtyproid:qtyproid,quantity:quantity,operation:operation,OrderType:OrderType},
            dataType: 'json',
            success:function(data)
            {
                var shoping =  '<sup>'  + data['data'][0] + '</sup>';
                $("#cartcount").html(shoping);
                $("#ftotalQty").text(data['data'][8]);
                $("#ftotalAmt").text(data['data'][9]);
                $("#fafterdistotalAmt").text(data['data'][10]);
    
              var oTable = $('#product_table').DataTable();
                oTable.ajax.reload( null, false ); 
    
                return false;
    
            }
    
        });
    
    }
    else
    {
        alert("Please enter quantity");
    }
    

    });

    foreach($result as $row) {

    $price=$row['Wholesale']; 
    $DiscountedPrice =$row['DiscountedPrice']; 
    setlocale(LC_MONETARY, 'en_US.UTF-8');
    $price =money_format('%.2n', $price);
    $DiscountedPrice =money_format('%.2n', $DiscountedPrice);
    $DiscountedPercent =  number_format($row['DiscountPricePer'],0);
    
    $sub_array = array();
    $sub_array[] = $row['Id'];
    $sub_array[] = $row['AvailableQTY'];
    $sub_array[] = $price;
    $sub_array[] =   '              
    <div id="inputdiv" class="input-group">
        <span>
            <input type="text" id="quantity'. $row['Id'] .'" name="'. $row['Id'] .'" class="myTextBoxes" value="'.  $row["Qty"] . '"maxlength="5" size="2" "min="0" max="1000">
        </span>
    </div>
    ';
    $sub_array[] ='$'.  $row['Total']; 
    $sub_array[] = $DiscountedPercent;
    $sub_array[] = $DiscountedPrice;
    $sub_array[] ='$'. $row['DiscountedTotal']; 
    
    $data[] = $sub_array;
    

    }

    $output =array(
    "draw" => intval($_POST["draw"]),
    "recordsTotal" =>count_all_data($db),
    "recordsFiltered" => $number_filter_row,
    "data" => $data

    );

    echo json_encode($output);
    
  • allanallan Posts: 63,534Questions: 1Answers: 10,475 Site admin

    Do you have a need to reload the table on change? I'm not clear on why you are doing that?

    Allan

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

    because I pulling updated rows from database and it seems to working correctly if change the value and click other next textbox. my page does move to top.

    But I will also try to set the values with reloading the datatable.

  • ganesh09ganesh09 Posts: 7Questions: 1Answers: 0

    How will get row index change event.
    want to set value to column oTable.cell(rowIndex, 13).data("$100.00");

  • kthorngrenkthorngren Posts: 21,343Questions: 26Answers: 4,954

    The cell().data() API is a client side processing method. Since you have server side processing enabled cell().data() won't do anything. You will need to update the server DB and refresh the data via ajax.reload() like you are doing now.

    Kevin

Sign In or Register to comment.