views:

630

answers:

5

I want to have a text field where people can type in a value. Then I want to have a href open a url with the text field appended to the end.

So if the text field says "elephant" then when they click the link, a page will open with at example.com/elephant.

I think javascript would be the easiest way to accomplish this but I just don't know how.

+3  A: 

I'm assuming that you have some HTML like the following and want to append the contents of the appendUrl input field to the url in the anchor tag when the anchor tag is clicked.

<a href="/base/url" id="baseUrl">Link Text</a>
<input type="text" id="appendUrl" />

Then, using jQuery, it would look something like:

$(function() {
    $('#baseUrl').click( function() {
        window.location = $(this).attr('href') + '/' + $('#appendUrl').val();
        return false;
    });
});

The basic idea is to extract the value of the input and append it to the url in the href. Use the value so constructed to set the location of the current window. I return false in the click handler to prevent the default action (the base url alone) from being taken.

tvanfosson
Thanks, worked out perfect.
+1  A: 
<input type="text" id="suffix" />
<a href="http://example.com/" onclick="document.location.href = $(this).attr('href')+$('#suffix').val(); return false;">click me</a>
Eimantas
I would prefer solutions that keep the javascript separate from the mark up. Much easier to read and maintain.
tvanfosson
I agree with tvanfosson. The `onclick` attribute was deprecated years ago
Josh Stodola
@Josh: I agree with tvanfosson too, but `onclick` was never deprecated.
Crescent Fresh
+1  A: 

You want to ensure that you don't break the URL because someone decided to put in special characters.

So make sure to wrap #appendURL with a URLEncode/Decode plugin such as this one URLEncode

Jen
+1  A: 

Here is a library agnostic version of what you want:

Your HTML:

<input type="text" name="url_param" id="url_param" />
<input type="button" onclick="prepare_link();" value="Do it!" />

<a href="http://whatever.com" id="target_link">Click Your New Link!</a>

Your Javascript:

<script type="text/javascript">
     function prepare_link() {
          var url_param = document.getElementById('url_param');
          var target_link = document.getElementById('target_link');

          if ( ! url_param.value ) {
               return false;  
          }

          target_link.href = target_link.href + '/' + escape(url_param.value);
     }
</script>

This is not the cleanest way to write the code and not how I would do it, but I tried to make it as simple as possible in the most generic way so that you'd be able to understand the code.

Eric Ryan Harrison
A: 

let say i put number in text field and want to redirect link like http://abc.com/number_from_text_field.html

means i want to add .html after click.

how can we achieve that?

manoj