Home > front end >  How to add a value to submitted form using JS
How to add a value to submitted form using JS

Time:08-02

I have the following html code:

<form>
      <input autofocus type="text" name="rnum" id="rnum"  placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
        document.getElementById('rnum')
        .addEventListener('keyup', function(event) {
               if (event.code === 'Enter') {
                  .append(window.location.search)
                  .toString();
                  event.preventDefault();
                  document.querySelector('form').submit();
               }
        });</script>

I have a search data in window.location that I want to add to the submitted value of the form. For instance, the url is:

http://127.0.0.1:5000/result?searchbox=cor

and the value of the form is rnum=10 that I want to combine and make:

http://127.0.0.1:5000/result?searchbox=cor&rnum=10

CodePudding user response:

well, you can create an input node with the desired value within the form and then submit it.

<form>
      <input autofocus type="text" name="rnum" id="rnum"  placeholder="Number of rows in a page">
</form>
<script type="text/javascript">
        document.getElementById('rnum')
        .addEventListener('keyup', function(event) {
               if (event.code === 'Enter') {
                  let child = document.createElement('input');
                  child.name = "searchBox";
                  child.value = window.location.search.toString();
                  event.preventDefault();
                  var form = document.querySelector('form');
                  form.appendChild(child);
                  form.submit()
               }
        });</script>

CodePudding user response:

There's a couple possible solutions here and here, you could go there to figure out the solution you need.

CodePudding user response:

I think you have a syntax error in this part

if (event.code === 'Enter') {
 .append(window.location.search) 
                  .toString();// this is an error since we are not appending the string anywhere
                  event.preventDefault();
                  document.querySelector('form').submit();
               }
  • Related