Change input text value in before submitting form

Shell Suite picture Shell Suite · Nov 15, 2017 · Viewed 10.1k times · Source

I'm trying to change the value of my input text field before submitting the form using jQuery like this:

<form actions="http://test.com/" method="GET">
 <input name="test" id="autocompleteform" type="text"/>
</form>
<script>
$('#form-customer-attr-new').submit(function(e) {
    var value = $("#autocompleteform").val();
    value = value.substr(0, value.indexOf(' '));
    if (!isNan(value) && !empty(value)) {
        $("#autocompleteform").val(value);
        alert($("#autocompleteform").val());
        return true;
    } else {
        alert("Invalid Postcode");
        return false;
    }
});
</script>

when i alert the value of the input file, it's showing the new value, but when the form submitten, the paramether in url still showing the old value of the input, for example:

 old_input_value = "1234 justice spoiler message";
 new_input_value = "1234";
 the_url_after_form_submit_now = "http://test.com?test=1234+justice+spoiler+message";
 the_url_after_form_submit_should_be ="http://test.com?test=1234";

Answer

Mehmet Emre Vural picture Mehmet Emre Vural · Nov 15, 2017
<form action="" id="form_id">
    <input type="text" name="change_value" id="change_value">
    <input type="text" name="d" id="d">
    <input type="submit" name="">

</form>    

$("#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.submit();//submit form
    });