Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form Input to Change URL

Tags:

html

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 Answers

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>
like image 62
Jonathan Lam Avatar answered Oct 31 '25 11:10

Jonathan Lam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!