2

I want to take a variable derived from an HTML form submission, and place it inside of a window.location.replace link.

HTML:

<form action="search.js" type="search">
     <input type="text" name="searchInput" class="textbox" placeholder='' maxlength="10" />    
</form>

On form submission, I've assigned searchInput to a JS variable.

Then, I want to place it after the ?query= in the link below:

https://www.youtube.com/channel/.../search?query=SEARCHINPUT

Is there a way to do this using JavaScript like below? Or is there a better solution using PHP?

window.location.replace="https://www.youtube.com/channel/.../search?query=[var=searchinput]

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Joe Sakett
  • 55
  • 6

2 Answers2

2

Yes, do this:

window.location.replace=".../search?query=" + $("[name=searchInput]").val();
Nir Tzezana
  • 2,275
  • 3
  • 33
  • 56
1

You could do this even just using the default form submit behavior if you change the action attribute of your form to the url you want to hit (without the query parameters), then change the name of your input to query.

<form action="https://www.youtube.com/channel/.../search">
    <input type="text" name="query" class="textbox" placeholder='' maxlength="10" />
    <button type="submit">Submit</button>
</form>

The default behavior of submitting a form will serialize your form values and place them after a ? at the end of the url in your action attribute.

So if you ran the above code, typed in 'search' in the input box, then clicked submit, your browser would be redirected to https://www.youtube.com/channel/.../search?query=search. (Note that this won't work in sanboxed environments such as StackSnippets, jsfiddle, etc., as they won't allow you to redirect to another domain, which is why I didn't make this a StackSnippet)

Andrew Mairose
  • 10,615
  • 12
  • 60
  • 102