Tarneem Tarneem - 7 months ago 23
Javascript Question

Name href Label According to User Text Input Javascrip

In my app, I am letting the user add categories. Each category is a simple href with label that the user entered as a name of category. The problem I am having is the category name is shown (undefined). So I am not sure where is the problem. Also, when I click again on add category, the previously created one disappear!



var boxName="type here";
var inputt = document.getElementById("boxName").value;
function addInput()
{
// var boxName="type here";

document.getElementById('responce').innerHTML='<br/><input type="text" id="'+boxName+'" value="'+boxName+'" /><input type="button" onclick="addlinking()" value="Add"/><span id="Adding"></span>';
var inputt = document.getElementById("boxName").value;
addlinking(inputt);

}
function addlinking(tt){
document.getElementById('Adding').innerHTML = '<br/><input type="submit" onclick="addinghref()" value="'+tt+'"><i class="fa fa-angle-right"></i></a><span id="Linking"></span>';

}
function addinghref()
{

document.getElementById('Linking').innerHTML='<a href="http://google.com"></a>';
}

<input type="button" onclick="addInput()" value="Add Category">
<span id="responce"></span>




Answer

var catTemplate = document.getElementById("adding-template")
                          .content
                          .querySelector(".category");
var createCatDiv = document.getElementById('create-cat');
var createCatInput = createCatDiv.querySelector("input[type=text]");

function addInput()
{
  // Clear previous entry.
  createCatInput.value = "";
  // Show the div.
  createCatDiv.classList.remove("hidden");
}

function addlinking()
{
  // Hide the create cat div.
  createCatDiv.classList.add("hidden");
  // Import the category div from the template.
  var catDiv = document.importNode(catTemplate, true);
  document.getElementById("response").appendChild(catDiv);
  // Set the input.
  var input = catDiv.querySelector("input");
  input.value = createCatInput.value;
  // Replace duckduckgo by the address of your link.
  input.onclick = location.assign.bind(location, "https://duckduckgo.com");
}
#create-cat {
  margin-top: 1em;
}
#create-cat.hidden {
  display: none;  
}
.category{
  margin-top: 1em;
}
.category input[type=button] {
  background-color: lightblue;
  border-style: solid;
  border-color: gray;
  border-width: 1px;
  border-radius: 5px;
}
.category input[type=button]:hover {
  background-color: blue;
  color: white;
  border-color: black;
}
.category input[type=button]:active {
  background-color: black;
  color: white;
  border-color: black;
}
<template id="adding-template">
  <div class="category">
    <input type="button" />
  </div>
</template>

<input type="button" onclick="addInput()" value="Add Category">
<div id="response"></div>
<div id="create-cat" class="hidden">
  <input type="text" placeholder="type here" />
  <input type="button" onclick="addlinking()" value="Add"/>
</div>