简体   繁体   中英

Change form POST data before submit with jQuery not working

I'm currently trying to change the value of a hidden input in my form during the form submit. So first I've my hidden input:

<input autocomplete="off" class="um-form-field valid not-required " type="text" name="webauthn_result-320" id="webauthn_result-320" value="" placeholder="" data-validate="" data-key="webauthn_result">

Now I'm using this function to do some things before the form submit. To get the results to the backend, I want to modify the form so that I can access them with $_POST in PHP:

jQuery(document).on('submit', '#login-form', function () {
    var someVarialbel = 20;
    jQuery('input[data-key=webauthn_result]').val(['success', someVarialbel]);
});

Sadly, it don't works. I've checked the backend and the value is empty. Any idea whats wrong?

Try something like this.

You will need to use preventDefault to make any changes.

$("#form_id").on("submit", function (e) {
    e.preventDefault();//stop submit event
    var self = $(this);//this form
    $("#change_value").val("deneme");//change input
    $("#form_id").off("submit");//need form submit event off.
    self.unbind('submit');
    self.submit();//submit form
});

From jQuery Documentation: Here is the link

For example, consider the HTML:

 <form id="target" action="destination.html"> <input type="text" value="Hello there"> <input type="submit" value="Go"> </form> <div id="other"> Trigger the handler </div> 

The event handler can be bound to the form:

 $( "#target" ).submit(function( event ) { alert( "Handler for .submit() called." ); event.preventDefault(); }); 

Now when the form is submitted, the message is alerted. This happens prior to the actual submission , so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. We can trigger the event manually when another element is clicked:

You can set value in JSON format as below:

jQuery(document).on('submit', '#login-form', function () {
    var someVarialbel = 20;
    jQuery('input[data-key=webauthn_result]').val(JSON.stringify(['success', someVarialbel]));
});

Hope it help you!

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