I need to dynamically change the href of an achor link on the screen to what the user is typing into an input box. I have jquery loaded if necessary or can use raw javascript.
Extra note that may or may not be important: The div that contains the input box and the anchor link is itself dynamic (may or may not be on the screen depending on the user's actions) so I am going to use the 'live' function of jquery to run the code whe开发者_运维知识库n the div box appears. This is necessary since I am using various posts to navigate through the website (it is for mobile web platforms).
Thanks for any help
Edit: Hey thanks for answers my question they are great and put me in the right direction but I have realised I didn't think through my question (sorry), what I want to actually do is append what they type onto the END of an existing href (it's a Get request to an api) So if they type 'example' it will add 'example' onto the href of 'www.apitest.com?variable='. It would be really helpful if you could tweak your example to do this. Thank you.
I don't know the structure of you page, so you need to replace $('input'), $('a') with selectors of input and anchor according to your page.
var apiUrl = 'www.apitest.com?variable=';
$('input').live('keyup', function(){
$('a').attr('href', apiUrl+$(this).val());
});
You can do this:
<div>
<input type="text" id="newAnchor" />
<p><a href="" id="addAnchor">Show Link</a></p>
</div>
Script
$('#newAnchor').live('keyup', function(){
var n = $(this).val();
$('#addAnchor').attr('href','#' + n);
});
http://jsfiddle.net/jasongennaro/Z39gt/
Hover over link at any time to see the change in the bottom bar.
EDIT
As per the comment, you should be able to place the new link you receive in a variable and reference it.
var link = 'http://www.apitest.com?variable=';
$('#newAnchor').live('keyup', function(){
var n = $(this).val();
$('#addAnchor').attr('href', link + n);
});
http://jsfiddle.net/jasongennaro/Z39gt/3/
精彩评论