Dynamically created list of files in JavaScript - javascript

I want to make a JavaScript code that created dynamically a list of files that i have
in a specific folder on my server. This list will be presented when i press a button
and each object will have a checkbox. The selected items will then be downloaded with another submit button and I guess some PHP.
So far I used JavaScript code I found online to find the names of the files and then call another function to create the elements but no luck.
function createEl(var a){
var myDiv = document.getElementById("cboxes");
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = a;
myDiv.appendChild(checkBox);
myDiv.appendChild(label);
label.appendChild(document.createTextNode(a));
}
function foldlist(){
const testFolder = './xampp/htdocs/website1/uploads';
const fs = require('fs');
fs.readdir(testFolder, (err, files) => {
files.forEach(file => {
var a=file;
createEl(a);
});
})}

You are trying to pass the var JavaScript keyword as a part of your createEl() function parameter.
Just change this:
function createEl(var a){
....
}
To this:
function createEl(a){
....
}
And your function should work fine. Check the Code Snippet below and you'll see that the function above is creating input-boxes as it should:
/* JavaScript */
function createEl(a){
var myDiv = document.getElementById("cboxes");
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = a;
myDiv.appendChild(checkBox);
myDiv.appendChild(label);
label.appendChild(document.createTextNode(a));
}
btn.addEventListener("click", function(){ createEl("hello") });
<!-- HTML -->
<button id="btn">Create input-box</button>
<div id="cboxes"></div>

Related

Using button in table and passing data from a cell in JavaScript

I'm trying to use javascript to retrieve the data from row.insertCell(0) unfortunately I don't believe I am setting up my this statement correctly so I am getting nothing back. I would appreciate some advice on this.
var cardTable = document.getElementById("cardBody");
card.forEach(item => {
let row = cardTable.insertRow();
let refNum = row.insertCell(0);
refNum.innerHTML = item.G1_Card_Ref;
let select = row.insertCell(1);
var sBtn = document.createElement('input');
sBtn.type = "button";
sBtn.className = "btn";
sBtn.style.color = "blue";
sBtn.setAttribute('onclick', 'editCard('this')');
sBtn.value = "Select";
select.appendChild(sBtn);
This is a temporary function I created to look at the data coming back from the table.
function editCard(CardRefNo) {
document.getElementById("ecForm").style.display = "block";
}
Try setting the onclick listener like this
sBtn.onclick = function() {
// do stuff with sBtn here, this is the new editCard function
console.log(sBtn)
document.getElementById("ecForm").style.display = "block";
}

Using JS to generate a list of HTML elements. addEventListener only applying to last element [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I have the following HTML written. The idea is that I can add items to the list at the top, and then generate a field which includes a name, checkbox, and text field. The text field is to be enabled/disabled depending on the checkbox. In my javascript, the toggle function is assigned to the onclick attribute of the checkbox field, but it only works on the last item on the list. Can anyone tell why this functionality isn't being assigned to all the checkboxes? If you open the resulting html code in a browser, it shows no onclick events for any checkboxes except the last one, so it appears it isn't being added. Does it somehow get removed from the previous one when I assign it to the next? How would I fix it? Thank you.
<!DOCTYPE html>
<html>
<body onload="loadAllSettings()" }>
<script>
var genOptFields = ["genField1", "genField2"];
function loadAllSettings() {
loadSettingsList("genSet", genOptFields);
}
</script>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
<script>
function loadSettingsList(parentId, optionalFields) {
var fieldset = document.getElementById(parentId);
for (fieldId of optionalFields) {
var p = document.createElement('p');
p.append(fieldId + ":");
var input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
var cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
cb.addEventListener("click", function () {
toggleCheck(fieldId);
});
p.appendChild(cb);
p.appendChild(input);
fieldset.appendChild(p);
}
}
function toggleCheck(fieldId) {
document.getElementById(fieldId).disabled = !document.getElementById("cb_" +
fieldId).checked;
}
</script>
</body>
</html>
As explained below, your fieldId reference isnt static. As a result when calling toggle check it was always passing the last value that fieldId contained no matter what (double check this by console.logging your fieldId passed to toggle check)
function loadAllSettings() {
const genOptFields = ["genField1", "genField2"];
loadSettingsList("genSet", genOptFields);
}
function loadSettingsList(parentId, optionalFields) {
const fieldset = document.getElementById(parentId);
optionalFields.forEach(function (fieldId) {
createParagraph(fieldId, fieldset);
});
}
function createParagraph(fieldId, fieldset) {
const p = document.createElement('p');
p.append(fieldId + ":");
createCheckbox(p, fieldId);
createInputField(p, fieldId);
fieldset.appendChild(p);
}
function createInputField(p, fieldId) {
const input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
p.appendChild(input);
}
function createCheckbox(p, fieldId) {
const cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
//set this attribute to capture value
cb.setAttribute('data-fieldId', fieldId);
cb.addEventListener("click", function () {
//use static data attribute value instead of fieldId var which isnt static
toggleCheck(this.getAttribute('data-fieldId'));
});
p.appendChild(cb);
}
function toggleCheck(fieldId) {
document.getElementById(fieldId).disabled = !document.getElementById("cb_" + fieldId).checked;
}
<!DOCTYPE html>
<html>
<body onload="loadAllSettings()" }>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
</body>
</html>
Since you are generating the element using body on-load event, click event become static. That is why element is always pointing to the last child. You can simply achieve your requirement by passing element scope(this) into the click event.
Here is the working solution:
<body onload="loadAllSettings()" }>
<script>
var genOptFields = ["genField1", "genField2"];
function loadAllSettings() {
loadSettingsList("genSet", genOptFields);
}
</script>
<h2>Options</h2>
<form>
<fieldset id="genSet">
<legend>General</legend>
</fieldset>
</form>
<script>
function loadSettingsList(parentId, optionalFields) {
var fieldset = document.getElementById(parentId);
for (fieldId of optionalFields) {
var p = document.createElement('p');
p.append(fieldId + ":");
var input = document.createElement('input');
input.type = "text";
input.disabled = true;
input.id = fieldId;
var cb = document.createElement('input');
cb.type = "checkbox";
cb.id = "cb_" + fieldId;
cb.addEventListener("click", function () {
toggleCheck(this);
});
p.appendChild(cb);
p.appendChild(input);
fieldset.appendChild(p);
}
}
function toggleCheck(ele) {
ele.nextElementSibling.disabled = !ele.checked;
}
</script>
</body>

javascript problems while generating form

everything working as my desire but when I click on book room button it can not generate input field for me but its shows as [object HTMLFormElement] here is my code
function booking(roomBooking){
var f = document.createElement("form");
var in1 = document.createElement("input");
in1.type = "text";
in1.name = "user_name";
in1.id = "user_name1";
f.appendChild(in1);
document.getElementById("name").innerHTML=f;
}
I want to show form when I clicked on book room button.
Here you are:
You should just apply your f variable to "#name" element by using appendChild() function, because "f" it's an object and you cannot directly use it.
function booking(roomBooking) {
var f = document.createElement("form");
var in1 = document.createElement("input");
in1.type = "text";
in1.name = "user_name";
in1.id = "user_name1";
f.appendChild(in1);
document.getElementById("name").appendChild(f);
}

Can't read value of checkbox with value, innerHTML or checked

I'm doing a basic (becuse I'm not skilled and just like to play around bulidning small things to learn) database project, setting things by checking checkboxes. However, when trying to check a box and read if it is checked or not checked it always reads "null". I've tried .value, .innerHTML and .checked. Nothing gets me there. All I'm trying to do is to pick up the input (i.e. checked or not checked) with getElementById and store it in a var, and later on compare if the boolean is true och false to set the value in the databas accordingly.
function createSheet() {
var _container = document.getElementById("container");
checkbox = document.createElement("input");
checkbox.type = "checkbox";
var valueOfId = document.getElementById("idString").checked;
Error messege: Cannot read property 'checked' of null.
EDIT: Thanks for the answers! I didn't show these lines since I didn't think they mattered that much, but I was wrong so here they are:
function createSheet() {
var _container = document.getElementById("container");
for (var i = 0; i < 4; i++) {
p = document.createElement("p");
spanBird = document.createElement("span");
checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "myCheck" + i;
checkbox.value = 0;
checkbox.checked = birds.birdList[i].seen;
spanBird.innerHTML = birds.birdList[i].name;
p.appendChild(spanBird);
p.appendChild(checkbox);
container.appendChild(p);
console.log(document.getElementById("myCheck" + i));
document.getElementById("myCheck" + i).addEventListener("click", readBox);
}
}
function readBox(){
getId();
theId = theId.substring(7);
console.log("idString: " + idString);
var valueOfId = document.getElementById("idString").checked;
}
and the HTML reads:
<section id="container">
</section>
/EDIT
Any suggestions?
Couple things:
You don't need document.getElementById, since you have checkbox already.
As stated by others, to use document.getElementById, you need to set a id to the checkbox Element. And you also need to add the element to the document.
checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "idString"
console.log(checkbox.checked)
document.body.appendChild(checkbox)
console.log(document.getElementById("idString").checked)
Actually, it's not that the property checked is null, your parent object is null.
I mean, this part:
document.getElementById("idString")
is returning null, so it can't access the checked property.
You need to first set the element's id with this
checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.setAttribute("id", "idString");
document.body.appendChild(checkbox)
var valueOfId = document.getElementById("idString").checked;
Then you should be able to access the value
In order to work you id first need create the attributes for your element like this.
You cant call by id if it isnt instantiate. Try out.
HTML
<div id="content"></div>
JAVASCRIPT
checkbox = document.createElement("input");
checkbox.setAttribute("id", "idString");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("value", "0");
var element = document.getElementById("content");
element.appendChild(checkbox);
var valueOfId = document.getElementById("idString").value;
console.log(valueOfId);

javascript button works in ie, not firefox or chrome

I'm writing a simple web page that displays a table. It the right column of the table I want to add a button in every row that says 'View'. I wrote a function that does this in ie by creating a button object and setting value = 'view' but in firefox and chrome the button displays with no text. Does anyone know why? Here is my code:
function addRow(id, sender, message){
var theTable = document.getElementById('messageTable');
var lastRow = theTable.rows.length;
var newRow = theTable.insertRow(lastRow);
newRow.id = id;
var cellLeft = newRow.insertCell(0);
var textNode = document.createTextNode(id);
cellLeft.appendChild(textNode);
var secondCell = newRow.insertCell(1);
var textNode2 = document.createTextNode(sender);
secondCell.appendChild(textNode2);
var messageCell = newRow.insertCell(2);
var messageNode = document.createTextNode(message);
messageCell.appendChild(messageNode);
var viewCell = newRow.insertCell(3);
var viewNode = document.createElement('button');
viewNode.value = 'View';
viewNode.onclick = function(){
alert('clicked: ' + id);
};
viewCell.appendChild(viewNode);
}
You have to do viewNode.innerHTML = 'View' since in FF button displays whatever is wrapped by the tag but not the value attribute
<button>s aren't self-closing like <input>s, and don't have a value attribute. You already have the solution in other parts of your code:
viewNode.appendChild(document.createTextNode('View'));
You also don't need to create variables for nodes that you're only using once. You can consolidate your code in a few places by using the above style.

Categories

Resources