Ad

Change Link Href Attribute On The Fly With Text Input Value

- 1 answer

I've got an input and a link. I need to change the link's href on the fly a.k.a when user types and it would be super great if there's a way to also detect if user pastes something in there.

Any idea how to achieve this via jQuery?

<input type="text" id="my-input">
<a id="my-link" target="_blank" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="www.something.com/<!--input text here-->/something/">
Click me!
</a>

What I've digged up:

//Somehow get the the input value if it has changed

//Change the href attribute
$("#my-link").attr("href", "//www.something.com/" + textFromInput +"/something/");
Ad

Answer

You should use the keyup event to handle typing on-the-fly

$('#my-input').keyup(
    function(){     
        var textFromInput = $("#my-input").val();
        $("#my-link").attr("href", "https://www.google.com?q=" + textFromInput); 
});

Check out this fiddle


You can also use change one, but it will fire when the input field's focus is lost - it will be ok too since you have to click on link to get effect (meaning you will have lost focus on input)

Ad
source: stackoverflow.com
Ad