4

I am in need of an HTML form in which the input would add onto a URL as I have a preexisting API.

Basically, I need an HTML form which would fill in a variable within a URL.

Say I had an API with the URL "https://example.com/api/api?item=<FILL THIS IN WITH THE INPUT>&auth=AUTHENTICATIONtoken", I need to have the input of the HTML form replace "<FILL THIS IN WITH THE INPUT>".

I recall finding a way to do this before-but I can't seem to find it anymore.

1 Answer 1

6

You can do this with JavaScript.

If this is your form:

<form onsubmit="changeFormAction()">
  <input type="text" id="item">
  <button type="submit" id="submitButton">Submit</button>
</form>

and if you have this in your JavaScript:

function changeFormAction() {
  var item = document.getElementById("item").value;
  var form = this;
  form.action = "https://example.com/api/api?item=" + item +  "&auth=AUTHENTICATIONtoken";
  form.submit();
}

Then the function will automatically change the form action by adding the item specified by the form input.


Demo:

function changeFormAction(event) {
  var item = document.getElementById("item").value;
  var form = this;
  form.action = "https://example.com/api/api?item=" + item + "&auth=AUTHENTICATIONtoken";
  
  // for demonstration, don't actually submit the form, just print out the form action
  console.log(form.action);
  event.preventDefault();
}
<form onsubmit="changeFormAction(event)">
  <input type="text" id="item">
  <button type="submit" id="submitButton">Submit</button>
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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