简体   繁体   中英

Modify form-data before post submit?

I have a really big form (too many values for a post request) and now I tried to minimy reduce the number of post parameters by summarizing the values line by line.

<form name="old_postform" method="post" action="https://example.com" />
    <input type="text" name="1_firstname" />
    <input type="text" name="1_lastname" />
    <input type="text" name="1_age" />
    <input type="text" name="2_firstname" />
    <input type="text" name="2_lastname" />
    <input type="text" name="2_age" />
    <input type="text" name="3_firstname" />
    <input type="text" name="3_lastname" />
    <input type="text" name="3_age" />
</form>

I already tried to react on the submit event of the form by interrupting this and submitting another form instead, but this didnt work well because I have some other values which need to be submitted too:

$('form[name="old_postform"]').submit(function (e) {
    let new_postform = '<form id="new_postform" method="post">';

    for(var i = 0; i < 1000; i++) {
        new_postform += '<input type="hidden" name="' + i + '" value="';
        new_postform += $('input[name=' + i + '_firstname' + ']').val() + ';';
        new_postform += $('input[name=' + i + '_lastname' + ']').val() + ';';
        new_postform += $('input[name=' + i + '_age' + ']').val() + ';';
    }

    new_postform += '</form>';
    $("#new_postform").submit();
});

Is there a simple way to remove all post parameters which start with a one, two or three digit from the old form and add my new post_form instead ?

I really would appreciate your help! ;)

you don't need to create another form to submit. Read all parameters and remove unwanted inputs from the form, add semicolon separated values as hidden input and submit the form.

See below code

$('form[name="old_postform"]').submit(function (e) {
    var $form = $(this);
    var $inputs = $form.find(":input");
    var len = $inputs.length/3; // calculate number of firstname, lastname and age per index

    for(var i=1; i<=len; i++){
      var $fn = $('input[name=' + i + '_firstname]');
      var $ln = $('input[name=' + i + '_lastname]');
      var $age = $('input[name=' + i + '_age]');
      var values = '<input type="hidden" name="' + i + '" value="';
        values += $fn.val() + ';';
        values += $ln.val() + ';';
        values += $age.val() + ';">';

        //remove read elements
        $fn.remove();
        $ln.remove();
        $age.remove();

       //append hidden input
       $form.append(values);
    };
    $form.submit();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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