Reputation: 1265
I'm attempting to dynamically create buttons with text loaded from a file into an array. The text loads, the array's created, but no buttons. I realize this has been asked before, but I must be doing something wrong.
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
/*
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
*/
function mkbuttons() {
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
$('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
</body>
</html>
Upvotes: 1
Views: 252
Reputation: 89
How do you think of this solution?
var database = [];
var total;
document.getElementById('file').onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent) {
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
database[line] = lines[line].trim();
}
total = line;
};
reader.readAsText(file);
};
function mkbuttons() {
for (let i = 0; i < total; i++)
$(document).ready(function() {
for (i = 0; i < total; i++) {
console.log(database[i]);
var newBtn = $('<button/>', {
text: database[i],
id: 'btn_' + i,
click: function() {
alert('hi');
}
});
$('#buttons').append(newBtn);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Create Buttons</title>
</head>
<body>
<input type="file" name="file" id="file" accept=".txt">
<br><br>
<button i onclick="mkbuttons()">Make Buttons</button>
<div id="buttons">
</div>
</body>
</html>
Upvotes: 2
Reputation: 3539
There are two glaring issues with your for loop:
$(document).ready
outside the function and only once. It should not be inside a for loopi
Once you fix this syntax things should work better, or at least be easier to debug..
Upvotes: 1