-1

Using javascript, I'm trying to do the following. I'll boil this down into it's simplest version.

I'd like to pass a variable from a text field to a URL, and have the URL be visited when the form is submitted.

  1. user enters a number into a text input field "123"
  2. user clicks the submit button
  3. Browser redirects to http://url.com/?myVariable=123 on click

The other question did not solve my problem because it didn't send a user-inputted variable.

Thank you.

Robert
  • 744
  • 1
  • 5
  • 15
  • 1
    Make the url string then redirect like [**this**](http://stackoverflow.com/questions/4744751/how-do-i-redirect-with-javascript)! – ibrahim mahrir Feb 10 '17 at 22:04
  • 4
    You don't even need JS to achieve that, it is the standard behavior for forms using GET method. Good reading http://www.w3schools.com/tags/att_form_method.asp. – Matteo Piano Feb 10 '17 at 22:05
  • 2
    Possible duplicate of [How do I redirect with Javascript?](http://stackoverflow.com/questions/4744751/how-do-i-redirect-with-javascript) – nicovank Feb 10 '17 at 22:14

2 Answers2

0

You can do it this way:

<form onSubmit="myFunction(); return false;">
    Enter name: <input id="myti" type="text"/>
    <input type="submit"/>
</form>

<script>
    function myFunction(){
        var currentUrl = window.location.href;
        window.location.href = currentUrl+"?"+ document.getElementById("myti").value;
    }
</script>
Antho
  • 35
  • 9
0

Interpretation

You want to redirect the user to

https://www.example.com/?myVariable=whatevertheusertyped

Solution

  • If you give the field an id attribute, it's value is accessible via Javascript, i.e. document.getElementById('id').value will give you the value of id (where id can be whatever you want as the id).

  • There is a Javascript variable window.location.href that, when changed, changes the URL of the page to what it was changed to.

Thus:

<input type="text" id="test"><br><br>
<button onclick="window.location.href='http://www.example.com?myVariable='+document.getElementById('test').value">Submit</button>
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55