Jordan A.
Jordan A.

Reputation: 384

How to use submit button to go to a URL with HTML

I am only starting to learn to code with HTML, so if this question seems trivial or simple, I apologise in advance.

Suppose I have a form, like

<form><input type="url" name="url"><input type="submit" value="Go"></form>

How do I make the submit button go to the url that the user types in?

Upvotes: 1

Views: 13165

Answers (2)

Daniel Congrove
Daniel Congrove

Reputation: 3669

In addition to the sending the user to the url when they hit submit, are you trying to save the url that is typed in?

If so you will need more than HTML to accomplish this, probably php + sql would be the easiest route to save it.

However, if all you're trying to do is let a user go to the url they are typing in, you could accomplish this through javascript or jquery.

For example in your html:

<form>
   <input id="url" type="url" name="url">
   <input type="button" value="Go" />
</form>

Then add this jquery:

$('input[type=button]').click( function() {
    var url = $('#url').text();
    $(location).attr('href', url)
});

Try this: http://jsfiddle.net/p6zxg25v/2/

Upvotes: 1

HaukurHaf
HaukurHaf

Reputation: 13796

You cannot do that using pure HTML. The form will always post/get to the URL which the action attribute of the form points to.

However, with some javascript you can do this.

This should work:

<form id="form" method="get">
   <input type="url" name="url" onchange="document.getElementById('form').action = this.value;">
   <input type="submit" value="Go">
</form>

What this does is it uses the onchange event of the url input box so everytime that changes, the action of the form is updated.

Upvotes: 4

Related Questions