user8408440
user8408440

Reputation:

Form Input to Change URL

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.

Upvotes: 4

Views: 12129

Answers (1)

Jonathan Lam
Jonathan Lam

Reputation: 17351

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>

Upvotes: 6

Related Questions