Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Dynamically Change href on user input

i want to change a link's href based on the user's input, so far i have this:

<input type="text" id="pdf" value="Enter ID" />
<a class="target" href="#">Download</a>

and

function URL() {
var newurl = $('#pdf').val();
$('a.target').attr('href', newurl);
}

However this is not working as it was supposed to. I simply want download url to be changed to the value of input text. So if i wrote "123" link would go to "123", but nothing is changing.

Probably i am missing something, i have read the answers about changing href dynamically, but i am kinda stuck here. Either this is not possible or i am doing something wrong.

Thanks

Edit: I mistakenly left the function and forgot to call it

Edit 2: It now gets the value from text box, but not dynamically changing.

like image 877
Tumay Avatar asked Feb 22 '23 12:02

Tumay


2 Answers

It's possible to alter the href, but have you bound a change listener to the input field?

This should to the trick:

$(document).ready(function() {
    $('#pdf').change(function() {
      var newurl = $('#pdf').val();
      $('a.target').attr('href', newurl);
    });
});
like image 114
svjson Avatar answered Mar 08 '23 13:03

svjson


You forgot to add the change event to the input. A nice short way of doing this is:

$("#pdf").live("change keypress keyup", function() {
     $("a.target").attr("href", (this).val());
});
like image 44
Herman Schaaf Avatar answered Mar 08 '23 11:03

Herman Schaaf