Reputation: 45
I'm working on a webpage where I have to get text from TextBox after it has text and put it inside anchor tag like this
<a href="value here">
I tried this solution but it works with button click only and i'm not able to set value between href="here"
HTML :
<input type="text" id="name" name="name">
<button onclick="myFunction()" name="btnView">View</button>
<a href="http://urlhere/valueFromTextbox">Name</a>
Javascript :
function myFunction() {
var test = document.getElementById("name").value;
document.getElementById("demo").innerHTML = test;
}
Please help. Thanks
Upvotes: 1
Views: 1318
Reputation: 109
Href is an attribute, if you want to change it you need to change the attribute using attr(). Create a listener to fire when the text box has input and change the href attribute
Upvotes: 0
Reputation: 28
try this it can be useful:
for the html:
<input type="text" id="name" name="name">
<a id="anchor" href="">Link</a>
<button type="button" onclick="foo();">Change link</button>
javascript function:
function foo(){
getHref = document.getElementById("name").value;
document.getElementById("anchor").href = "https://"+getHref;
}
Upvotes: 0
Reputation: 2255
You could listen for input- or change-events on the input-field and set the href-attribute of your anchor in the handler.
For example:
const input = document.getElementById('name');
const anchor = document.getElementsByTagName('a')[0];
input.oninput = () => {
anchor.href = input.value;
};
Enter href: <input id="name">
<a href="">Click here</a>
Upvotes: 3
Reputation: 208
What you are doing is setting innerHTML which is wrong. Anchor tags "href" is an attribute. You have to set it as an attribute, not innerHTML. Try this instead.
var test = document.getElementById("name").value;
document.getElementsByTagName("a")[0].setAttribute("href", text);
Upvotes: 0