Add Delete Button Dynamically - javascript

I have very little experience with Javascript.
My goal is to build a table from an array, and allow the user to delete items from the array as needed. I wanted to have a "delete" button next to each array item that is shown.
I'm open to other ideas of how to accomplish this. My code is here:
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
LLen = LargeList.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + LargeList[i] + "</li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = LargeList.join("/ ");
}
The target HTML:
<body>
<div>
<select id="LargeItems">
<option></option>
<option>LMIS</option>
<option>ARMC</option>
<option>BNCH</option>
</select>
<input type="button" onclick="AddLargeItem()" id="AddLargeItem" value="ADD LARGE" />
<span><p id="LargeCount"></p></span>
</div>
<p id="random"></p>
<p id="LargeInventory"></p>
</div>

I wanted to have a "delete" button next to each array item that is shown
To achieve your above requirement, you can modify the code as below.
<script>
var LargeList = ["¥"]
function AddLargeItem() {
LargeList.push(document.getElementById("LargeItems").value)
PopulateList(LargeList);
}
function PopulateList(arr) {
LLen = arr.length;
text = "<ol>";
for (i = 0; i < LLen; i++) {
text += "<li>" + arr[i] + "<input type='button' onclick='Delitem(" + i + ")' value='Delete' /></li>";
}
text += "</ol>";
document.getElementById("LargeInventory").innerHTML = text;
document.getElementById("LargeCount").innerHTML = LLen * 10;
document.getElementById("random").innerHTML = arr.join("/ ");
}
function Delitem(index) {
LargeList.splice(index, 1);
PopulateList(LargeList);
}
</script>
Test Result

There is two ways I can think of to do this.
num one:
assign the elements you want to delete and id ex: then use javascript to append the elements with your list. then onclick="remove('list')" and make a function like this
function remove(id){getElementById(id).remove()}
num two:
if you just want to use javascript def your list then get an integer from the user and use my something like this
index = getElementById('foo').value;
my_list = my_list[:foo] + my_list[foo+1:];
document.write(my_list);

Related

Nesting [innerHTML] in AngularJS

How can I 'nest' innerHTML bindings? Is it a sanitation problem?
I am using angular to create a website to play chess. I am dynamically creating a table and putting it into the component with: <div [innerHTML]="board | safeHTML"> where board with a string with the HTML for the table in and safeHTML is a pipe that bypasses sanitisation so the HTML isn't just read as a string. The code to generate the table is at the bottom of the post.
I would like to then be able to change the contents of each cell in the table.
Here is an example cell:
<td id="n${uniqueNumber}" class="board" [innerHTML]="boardValues.${uniqueNumber}">{{boardValues.${uniqueNumber}}}</td>
boardValues is an object that contains all of the cell data.
The table correctly displays when bound with [innerHTML] however the cells don't and [innerHTML] is displayed as an attribute (e.g. this image). Similarly {{boardValues.value}} shows up as plain text rather than the value.
How can I 'nest' innerHTML bindings? Is it a sanitation problem?
My html:
Running that doesn't work but it shows my main loops (the important one is generateBoard)
Here is a stack blitz project that sort of works but doesn't have formatting for some reason. Still shows my issue
generateBoard(n, playColour) {
var tblBuild = ""
var tblFooter = "<tr><td id=\"blank\"></td>"
for (var i = 0; i < 8; i++) {
tblFooter += `<th class="coordinates letters">${String.fromCharCode(97+i)}</th>`
}
tblFooter += "</tr>"
for (var i = 0; i <= n; i++) {
tblBuild += `<tr class="n${n-i+1}">`
tblBuild += `<th class="coordinates numbers">${n-i+1}</th>`
for (var j = 0; j <= n; j++) {
var idValue = `n${8*(n-i)+j}`
//want to assign the innerHTML to an object
tblBuild += `<td id="n${idValue}" class="board" [innerHTML]="boardValues.${idValue}">{{boardValues.${idValue}}}</td>`
}
tblBuild += ("</tr>")
}
var tbl = "<table id=\"board\" class= \"board " + playColour + "\"" + "<tbody>" + tblBuild + "</tbody>" + tblFooter + "</table>"
console.log(tbl)
return tbl
}
generateBoardValues(n) {
interface LooseObject {
[key: string]: any
}
var boardValues: LooseObject = {}
console.log("running generateBoardvalues")
console.log("n", n)
for (var i = 0; i <= n; i++) {
for (var j = 0; j <= n; j++) {
boardValues[`n${8*(n-i)+j}`] = `n${8*(n-i)+j}`
console.log("generating boardValues", boardValues[`n${8*(n-i)+j}`])
}
}
boardValues.n15 = "maually set"
console.log("n15", boardValues.n15)
console.log(Object.keys(boardValues).sort((a, b) => Number(a.slice(1)) - Number(b.slice(1)))) //sorted values
return boardValues
}
n = 7
boardValues = generateBoardValues(n)
board = generateBoard(n, "white")
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<p [innerHTML]="boardValues.n12"></p> <!--Works-->
<div [innerHTML]="board | safeHTML"> <!-- displays table but not desired cell contents-->
This approche is very expensive. I wouldn't use innerHTML in your case. You should handle this in your template file and use *ngFor.

Using The Input Value Instead Of The First Statement Of A Loop In JavaScript

I am trying to understand the insertion sort algorithm. I want to use an input button and diagram. When the user writes a number then click the button, my page will create random values. I found some snippets on the internet but they use i = 0. I want to use my input value instead of i = 0. How can I do it?
A part of my index.html:
<div id="buttons">
<a class="button" id="butonInsert" href="javascript://">insertion sort</a>
<a class="button" id="butonReset" href="javascript://">Reset</a>
<input type="number" id="myNumber" value="blabla">
<button onclick="reset()"></button>
A part of my script.js:
function reset() {
for (i=0; i<50; ++i) {
data[i] = ~~(i*160/50);
}
for (i=data.length-1; i>=0; --i) {
var ridx = ~~( Math.random() * ( data.length ) );
data.swap(i, ridx);
}
var tb = $("#sortPanel");
tb.empty();
var tr = $("<tr></tr>");
for (i=0; i<data.length; ++i) {
tr.append("<td id='b"+i+"'>" +
"<div class='cc' style='height: "+data[i]+"px;'>" +
"</div></td>");
}
tb.append(tr);
resetted = true;
}
I didn't quite understand what you are trying to do but if you just want to use an input's value you can easily get it with javascript and use it instead of i=0.
var inputValue = document.getElementById("myNumber").value ;
Then in your for statements :
for (var i = inputValue ; i < data.length; ++i) {
// code
}
Use document.getElementbyId('myNumber').value. This might work.

html list add and remove using and js [duplicate]

This question already has answers here:
JavaScript DOM remove element
(4 answers)
Closed 3 years ago.
I am trying to make a simple list using html input box and js. the list are creating on clicking "add skill" and get removed when click on "remove". But when I try to add some skill after remove, the last removed item also get back.
var skillList="";
var i = 0;
function addSkill(){
var skills= document.getElementById("addSkill").value;
if(skills != ""){
skillList += "<li><span name='skillItem' id='skillItem"+ i +"'>" + skills + "</span> " +
"<a onclick='removeSkill()'>remove</a></li>";
i++;
document.getElementById("skill").innerHTML = skillList;
document.getElementById("addSkill").value="";
}
}
function removeSkill(){
skillList="";
var items = document.querySelectorAll("#skill li"),index,tab = [];
for(var j = 0; j < items.length; j++){
tab.push(items[j].innerHTML);
}
for(var j = 0; j < items.length; j++){
items[j].onclick = function(){
index = tab.indexOf(this.innerHTML);
items[index].parentNode.removeChild(items[index]);
tab.splice(j,1);
};
}
console.log(tab);
for(var j=0; j<tab.length;j++){
skillList += "<li>" + tab[j] + "</li>";
}
}
<td><label>skills:</label></td>
<td>
<ul id="skill"></ul>
<input type="text" name="skill" id="addSkill"/>
<a onclick="addSkill();" value="">add skill</a>
</td>
Just delete this piece of code
for(var j=0; j<tab.length;j++){
skillList += "<li>" + tab[j] + "</li>";
}
Your were adding it again...
Working now...
var skillList="";
var i = 0;
function addSkill(){
var skills= document.getElementById("addSkill").value;
if(skills != ""){
skillList += "<li><span name='skillItem' id='skillItem"+ i +"'>" + skills + "</span> " +
"<a onclick='removeSkill()'>remove</a></li>";
i++;
document.getElementById("skill").innerHTML = skillList;
document.getElementById("addSkill").value="";
}
}
function removeSkill(){
skillList="";
var items = document.querySelectorAll("#skill li"),index,tab = [];
for(var j = 0; j < items.length; j++){
tab.push(items[j].innerHTML);
}
for(var j = 0; j < items.length; j++){
items[j].onclick = function(){
index = tab.indexOf(this.innerHTML);
items[index].parentNode.removeChild(items[index]);
tab.pop(j,1);
};
}
}
<td><label>skills:</label></td>
<td>
<ul id="skill"></ul>
<input type="text" name="skill" id="addSkill"/>
<a onclick="addSkill();" value="">add skill</a>
</td>
You got all lost in the loops and indexes in your removeSkill function and it's way easier than what you are doing - one single line of code. No loops and no arrays are needed.
You've also got a bunch of other styles of coding that are ancient and should be avoided.
You don't need to use a hyperlink just because you want to give
someone something to click on. All visible elements support a click
event. Only use hyperlinks when you are actually navigating
somewhere.
You can't use table cells without a table.
Don't use inline HTML event attributes (onclick). Separate all your
JavaScript from your HTML and do the event binding with
.addEventListener().
Don't create new HTML by concatenating strings together. It becomes a
nightmare fast and requires you to use .innerHTML, which has
performance and security implications. Instead, create new DOM
objects, configure their properties as needed and then append them
into the document.
See the comments inline below:
// Get all the element references you'll need just once:
var skillList = document.querySelector("#skillList");
var newSkill = document.querySelector("#newSkill");
var btnAddSkill = document.querySelector("input[type='button'");
// Do all of your event binding in JavaScript, not with inline HTML event attributes
btnAddSkill.addEventListener("click", addSkill);
function addSkill(){
if(newSkill.value !== ""){
// Don't build new HTML by concatenating strings. Create elements and configure them as objects
var li = document.createElement("li");
li.textContent = newSkill.value;
// Only use hyperlinks for navigation, not to have something to click on. Any element can be clicked
var span = document.createElement("span");
span.classList.add("remove");
span.textContent = "remove skill";
span.addEventListener("click", removeSkill);
li.appendChild(span); // Add the span to the bullet
skillList.appendChild(li); // Add the bullet to the list
newSkill.value = "";
}
}
function removeSkill(){
// Just remove the closest <li> ancestor to the <span> that got clicked
skillList.removeChild(this.closest("li"));
}
.remove { display:inline-block; margin-left:10px; padding:2px 4px; background:rgba(200,0,225,.7); color:#ff0; cursor:pointer; }
li {margin:8px 0; border-bottom:1px dashed #e0e0e0; }
<h1>Skills:</h1>
<input type="text" name="skill" id="newSkill">
<input type="button" value="add skill">
<ul id="skillList"></ul>

JSON - How to give onclick element in script?

How to give onclick function for id in JavaScript? eg: my onclick function is oclick="function('#id')" and I need action to be made in div. My each buttons contain their own id's. But I couldnt figure out how to use this element to generate using JSON.
I prefer JavaScript rathar than jquery.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<button onclick="function('#' + arr[i].ids + '')">' +
arr[i].blaah + '</button><br>';
}
document.getElementById("id01").innerHTML = out;
}
Do you need something like this?
var arr = ["id1", "id2", "id3", "id4"]
function onClick() {
alert("you clicked button with id: " + this.id);
}
function createButtons(arr) {
var out = document.getElementById("out");
for (var i = 0, l = arr.length; i < l; i++) {
var node = document.createElement("button");
node.id = arr[i];
node.innerHTML = "button " + arr[i];
node.addEventListener("click", onClick, false);
out.appendChild(node);
}
}
createButtons(arr);
<div id="out">
</div>
Simple solution: use this
function yourfunction(elem){
//elem contains the button
//you could do:
elem.style.display="none";
}
In your html do:
<div onclick="yourfunction(this)">Button</div>
For shure this can be created dynamically.
If you want to keep your code, dont get confused with " and ' .
" ' " for example: the second " closes the first, even if theres an opened '. And you cannot name a function function. Thats an syntax error. Do this:
"<button onclick=\'func('#elem')\' >test</button>";

format text fields created

I'm really new so I'll appreciate some help here. please refer to this fiddle.
$(function () {
var input = $('<input type="text" />');
$('#qty').bind('blur', function () {
var n = this.value || 0;
if (n + 1) {
setFields(n);
}
});
function setFields(n) {
$('#newFields').html("");
$('#newFields').append("<table>");
//to create rows and columns
for (i = 0; i < n; i++) {
for (j = 0; j < 1; j++) {
var somestr = "Sample ";
var num = i + 1;
$('#newFields').append("<td>" + somestr + num + ":" + "</td>");
$('#newFields').append("<td>");
var newInput = input.clone();
var newFields1 = $('');
newFields1 = newFields1.add(newInput);
newInput.appendTo('#newFields');
$('#newFields').after("</td>");
}
$('#newFields').after("</tr>");
}
}
});
I'll like to have the input text field appear on the right column (so it should be [column 1]"Sample #" [column 2] input text field, with "Sample 2" and another text field appearing on the next row and so forth). Been trying but couldn't get it. Thanks!
Try appending new rows to the existing table by targeting the table itself on the appendTo() method. You don't need to add a new table and, as you haven't been closing the table off with </table> this isn't working at present anyway.

Categories