JQuery how to submit only changed fields when the form has some data array

后端 未结 3 1556

I have a database structure with an one to many relationship. In the html form, there are similar inputs with a name \'item[]\' or \'file[]\' to make the data to be an array

3条回答
  •  迷失自我
    2021-01-14 22:48

    You can add the "changed" class to desired elements on change and send data of elements those have not the class "changed":

    Name:
    Item:
    File: Item:
    File: Select:

    listening for changes:

    $("input,select").on("change",function(){
       $(this).addClass("changed");
    })
    

    handle data by ajax call and prevent form submission by return false and reset the changed class to nothing:

    $("#myform").on("submit",function(){
    
    //Collecting data from changed class:
    var data;
    $(".changed").each(function(){
    data=data+$(this).attr("name")+":"+$(this).val()+",";
    });
    
    //just removing last comma:
    data=data.substring(0, data.length - 1);
    
    //Submit data:
    $.ajax({
        ...
        data : { data },
        ...
        success: function(){ 
        //Removing changed class from all elements
        $(".changed").removeClass("changed");
        }
    });
    
    return false;
    });
    

提交回复
热议问题