Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set backgroundcolor and border for each array element using javascript or jquery?

I am trying to set separate background and border for each element in the array using JavaScript something like this. Until now what I have done outputis below. As I add a new element to the array, it will stretch the background.

let skills = [];

function displayname() {
  console.log(document.getElementById("namehere").value);
  x = document.getElementById("namehere").value;
  skills.push(x);
  console.log(skills)
  document.getElementById("skill-set").innerHTML = skills
  document.getElementById("skill-set").style.border = "1px solid blue";
  document.getElementById("skill-set").style.backgroundColor = "yellow";
  document.getElementById("skill-set").style.padding = "5px";
  document.getElementById("skill-set").style.display = "inline-block";
  document.getElementById('namehere').value = " ";
}
<label>Enter the skills: </label><br>
<input type=t ext id="namehere" onchange="displayname()">
<div id="skill-set"></div>
like image 913
Mohammed zuhair Avatar asked Dec 23 '22 16:12

Mohammed zuhair


1 Answers

Why not create div ? like:

function displayname(el) {
  var skilldiv = document.getElementById("skill-set");
  var div = document.createElement("div");
  div.classList.add("mystyle");
  var content = document.createTextNode(el.value); 
  div.appendChild(content);  
  skilldiv.appendChild(div);
}
#skill-set div {
  display: inline-block;
  border: 1px solid blue;
  background-color: yellow;
  padding: 5px;
  margin: 5px 5px 0 0;
}
<label>Enter the skills: </label><br>
<input type="text" id="namehere" onchange="displayname(this)">
<div id="skill-set"></div>

Everytime you set new skill, function will create a new div.

Edit from your comment:

function displayname(el) {
  var skilldiv = document.getElementById("skill-set");
  var div = document.createElement("div");
  div.classList.add("mystyle");
  var content = document.createTextNode(el.value); 
  div.appendChild(content);  
  skilldiv.appendChild(div);
}
#skill-set div {
  display: inline-block;
  border: 1px solid blue;
  background-color: yellow;
  padding: 5px;
  margin: 5px 5px 0 0;
}
<label>Enter the skills: </label><br>
<select name="namehere" id="namehere" onChange="displayname(this)">
  <option value=""></option>
  <option value="java">Java</option>
  <option value="php">PHP</option>
  <option value="html">Html</option>

</select>
<div id="skill-set"></div>
like image 144
Simone Rossaini Avatar answered Dec 25 '22 06:12

Simone Rossaini