0

I'm sorry this is probably very basic but I'd like to pass a variable from one page to another. I have one page with a list of names and the next page is a form. One of the inputs on the form is for a name. I'd like to fill the value of this name input with the name that was clicked on from the list of names.

For instance, this is the list of names that link to the form when clicked on:

<a href="form.html" id="John Doe">John Doe</a>
<a href="form.html" id="John Smith">John Smith</a>
<a href="form.html" id="Jane Doe">Jane Doe</a>

form.html would look like this:

<form>
<input name="name" type="text" value=""/>
</form>

I'd like the value of the text input to change depending on which name was clicked. I'd prefer to do it with javascript but whatever you guys think is best.

2
  • Are you using any sort of server-side processing (i.e. PHP, Python, Perl, etc.)? Or do you need a strictly Javascript solution? Commented Jan 29, 2013 at 17:53
  • I'd like to use just javascript but I'm willing to use php is necessary. However, the answers below have solved the issue with just javascript so thanks! Commented Jan 29, 2013 at 18:25

2 Answers 2

2

You'll have to pass it in the query string:

<a href="form.html?name=John+Doe" id="John Doe">John Doe</a>
<a href="form.html?name=John+Smith" id="John Smith">John Smith</a>
<a href="form.html?name=Jane+Doe" id="Jane Doe">Jane Doe</a>

Then, in form.html, use the following to get the name:

var name = (window.location.search.match(/name=([^&]+)/) || [])[1];
Sign up to request clarification or add additional context in comments.

Comments

0

You could use a query string, parse it with Javascript, then place the value in your input.

Add an id or something on your text input for you to refer to your input.

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (decodeURIComponent(pair[0]) == variable) {
        return decodeURIComponent(pair[1]);
    }
}
console.log('Query variable %s not found', variable);
}

var name = getQueryVariable('name');

document.getElementById('myInput').value = name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.