Andrew
Andrew

Reputation: 509

Pass javascript variable via form (get)

Ok, so the idea is that I have some javascript stuff happening (autcomplete) that ends up creating a variable. Let's declare the variable as test and have the value of testValue.

I then have a form further down the page and I want to append this value of test to the submission of a form.

Eg. I have a form:

<form name="form" method="get" action="search.php">
    <input id="search" name="search" type="text" value="Search" size="40" />
</form>

What I want to do is change the action from search.php to:

search.php?test= our javascript variable's value

Seems pretty basic and is very achievable in php. Eg. in PHP:

<?php
  $test = "somevalue;
  $url = "search.php?test=$test"
?>

Etc.

How can I achieve this in javascript

Upvotes: 0

Views: 233

Answers (1)

Quentin
Quentin

Reputation: 944054

Leave the action alone. You are trying to modify the data in the query string.

Generate a hidden input and add it to the form.

var i = document.createElement('input');
i.type = 'hidden';
i.name = 'test';
i.value = foo;
document.forms.id_of_form.appendChild(i);

Upvotes: 1

Related Questions