1

Let's say we have the following form:

<form action="someaction" method="post">
    <input type="hidden" id="input_example" name="input_example" value="">
    <button type="submit" id="show-selected" class="btn btn-primary">Submit</button>
</form>

The value before clicking on the Submit button is "", but I would like that before sending the form, when clicking on the submit button, to be able to inject a value into the input from JavaScript.

For example:

$( "#show-selected" ).click(function() {
    //add some value to the input, like "abc" and then submit the form
    //I guess we could do something like:
    //document.getElementById("#input_example").value = "abc";
    //
});

But how can we do so that the value is injected before sending the form and not after?

1
  • 1
    If you listen for the "submit" even of the "form" element (rather than the "click" event of the "submit" button), then the script will run at the time of form submission, and updated element values will be POST-ed with the form. javascript.info/forms-submit Commented Apr 26, 2021 at 4:20

2 Answers 2

1

Prevent the form from being submitted using preventDefault method of submit button click, change the value of the input and submit the form.

<form action="someaction" method="post" id="form">
    <input type="hidden" id="input_example" name="input_example" value="">
    <button type="submit" id="show-selected" class="btn btn-primary">Submit</button>
</form>

<script>
    document.getElementById("show-selected").addEventListener("click", function (event) {
        event.preventDefault();
        document.getElementById("input_example").value = "abc";
        document.getElementById("form").submit();
    });
</script>
Sign up to request clarification or add additional context in comments.

Comments

1
$( "#show-selected" ).click(function(e) {

  e.preventDefault();// you will need this first to prevent the form submit
  $('#input_example').val('abc');
  let hiddenVal = $('#input_example').val();
  alert('The value of hidden input is: ' + hiddenVal)

  // Add the form ID to submit it later
  $("#formID").submit();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.