Home > Net >  Javascript Link to Href maker not working
Javascript Link to Href maker not working

Time:03-26

I'm trying to make a simple link to html maker, but the thing is variables aren't working

var text1 = document.getElementById("text1");
var link1 = document.getElementById("link1");
var input = document.getElementById("thetext");
var flink1 = "<a href='"   link1.value   "'>"   text1.value   "</a>";

function generate() {
  input.value = flink1
}
input,
textarea {
  width: 100%;
  height: 50px
}
<textarea id="thetext" ></textarea>
<br/><br/>
<input id="link1" placeholder="link"></input><br/><br/>
<input id="text1" placeholder="link title"></input><br/><br/>
<button id="" onclick="generate()"></button>

Can anyone say what's the issue

CodePudding user response:

Your flink1 will always contain empty strings for href and innerText because your generate doesn't update its value upon user input.

Move the variable definition inside generate call, and it'll work as intended.

var text1 = document.getElementById("text1");
var link1 = document.getElementById("link1");
var input = document.getElementById("thetext");

function generate() {
  var flink1 = "<a href='"   link1.value   "'>"   text1.value   "</a>";
  input.value = flink1
}
input,
textarea {
  width: 100%;
  height: 50px
}
<textarea id="thetext" ></textarea>
<br/><br/>
<input id="link1" placeholder="link"></input><br/><br/>
<input id="text1" placeholder="link title"></input><br/><br/>
<button id="" onclick="generate()">Generate</button>

CodePudding user response:

This is your answer.

function generate() {
var text1 = document.getElementById("text1");
var link1 = document.getElementById("link1");
var input = document.getElementById("thetext");
var flink1 = "<a href='"   link1.value   "'>"   text1.value   "</a>";
input.value = flink1;
}
input,
textarea {
  width: 100%;
  height: 50px
}
<textarea id="thetext" ></textarea>
<br/><br/>
<input id="link1" placeholder="link"></input><br/><br/>
<input id="text1" placeholder="link title"></input><br/><br/>
<button id="" onclick="generate()">Generate</button>

  • Related