Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
When I click the roll button, nothing happens. Is there a way to show the results using document.getElementByID("results").innerHTML, or is this not recommended?
HTML
<p>How many dice?
<br/>
<input type="text" id="numDice" />
</p>
<p>How many sides per die?
<br/>
<input type="text" id="numSides" />
</p>
<button onclick="diceRoll()" id="roll"/>Roll!</button>
<p id="results"></p>
JavaScript
var numDice = document.getElementByID(numDice).innerHTML;
var numSides = document.getElementByID(numSides).innerHTML;
function diceRoll() {
var results = "";
for (var i = 0; i < numDice; i++) {
results += (Math.random() * numSides) + 1;
}
document.getElementByID("results").innerHTML = results;
}
CodePen
Typo, it's not
getElementByID
but
getElementById
The case is important, and the arguments passed are strings, so they should be quoted
function diceRoll() {
var numDice = document.getElementById('numDice').value;
var numSides = document.getElementById('numSides').value;
var results = "";
for (var i = 0; i < numDice; i++) {
results += (Math.round(results + (Math.random() * numSides) + 1)).toString();
}
document.getElementById('results').innerHTML = results;
}
FIDDLE
You are calling document.getElementByID(numDice).innerHTML before the DOM is ready. The element does not exist, so this will throw an error.
You want to get the values each time diceRoll() is called, so that you get the values the user entered. numDice will not automatically update when the value changes.
P.S. It's getElementById, and you want to use .value() for <input>s.
function diceRoll() {
var results = "";
var numDice = parseInt(document.getElementById('numDice').value, 10);
var numSides = parseInt(document.getElementById('numSides').value, 10);
for (var i = 0; i < numDice; i++) {
results += (Math.random() * numSides) + 1;
}
document.getElementById("results").innerHTML = results;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to define an array inside of a loop so that it defines an item in the array as it increments. I am also trying to set the array item to another array item. However, I've tried multiple formats and I keep getting Unexpected Token [
var filename = [];
var i = 0;
for (span.innerHTML = ""; i < files.length; i++) {
span.innerHTML += files[i].name + " <input type='text' name='" + type + i + "' placeholder='Display Name' onchange='aupdate(undefined)'>" + "<br>";
var filename[i] = files[i].name;
}
You don't need to declare a new variable - and variables names cannot contain [ or ] (only the alphabet, numbers, _ and $):
var filename = [];
var i = 0;
for (span.innerHTML = ""; i < files.length; i++) {
span.innerHTML += files[i].name + " <input type='text' name='" + type + i + "' placeholder='Display Name' onchange='aupdate(undefined)'>" + "<br>";
filename[i] = files[i].name;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have this:
var divProducthere= document.getElementById('divProducthere'); //div
var productbutton = document.getElementById('productbutton'); // button
productbutton.addEventListener('click',prodElement);
function prodElement(){
for (var i = 0; i < 9; i++) {
var selectProduct = document.createElement('select');
selectProduct.id = 'r'+i;
divProducthere.appendChild(selectProduct);
}
this does not work for me, because I just need to create the elements with the click event, one by one, but assigning unique id to each of the created elements
Put the counter in a global variable.
var select_counter = 0;
function prodElement() {
select_counter++;
var selectProduct = document.createElement('select');
selectProduct.id = 'r'+select_counter;
divProducthere.appendChild(selectProduct);
}
You can create a unique id like this:
function uniqId(length = 6) {
return (Math.random().toString(36) + Math.random().toString(36)).substr(2, length);
}
for (let i = 0; i < 10; i++) {
console.log(uniqId(parseInt(Math.max(2, Math.random() * 10))))
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have been trying to create a table dynamically based on an array return from another function.
I have 2 array :
var listOfNames = ['a', 'b', 'c'];
var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];
The first array will contain element which will be id of each row.
The second array is the list of columns for each row.
My html looks like this
<table>
<tbody></tbody>
</table>
and the for loop that I have written looks like this :
for (var i = 0; listOfNames.length < i; i++) {
var row = $('<tr></tr>');
$(row).attr('id', listOfNames[i]);
for (var x = 0; scoreLabels.length < x; x++) {
var tableHeader = $('<td></td>');
$(tableHeader).attr('text', scoreLabels[x]);
$(tableHeader).appendTo(row);
}
$(row).appendTo('table');
}
I have been looking at other posts that teaches the creation of table dynamically with jquery, but to no avail.
Please kindly advice and let me know where i went wrong .
The js fiddle can be found here
http://jsfiddle.net/t16scofy/2
For-loops...
Just read your for-loops out loud:
for (var i = 0; listOfNames.length < i; i++) {...}
becomes:
for i - starting at 0 - do ... as long as the length of listOfNames is smaller then i.
I starts at 0. and the length of listOfNames is always larger then 0. It is never smaller. so this for loop will never do ...
Same goes for you inner for-loop
corrected:
for (var i = 0; i < listOfNames.length; i++) {...}
or if you really want the i after the .length:
for (var i = 0; listOfNames.length > i; i++) {...}
You have a few typos and wrong conditions in both your for loops.
This should do it:
var listOfNames = ['a', 'b', 'c'];
var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];
// If i starts with 0, and you're incrementing it, you obviously want the loop
// to go until it reaches a bigger value, not the other way round.
for (var i = 0; i < listOfNames.length; i++) {
var row = $('<tr>', { class: i.toString() });
// If x starts with 0, and you're incrementing it, you obviously want the loop
// to go until it reaches a bigger value, not the other way round.
for (var x = 0; x < scoreLabels.length; x++) {
var tableHeader = $('<td>', { text: scoreLabels[x] });
tableHeader.appendTo(row);
}
row.appendTo('table');
}
Demo
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a small script that should detect duplicate elements in an array of fields on a form.
function dupes() {
var unique = [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
unique[i] = Number(document.getElementById('proj' + i).value);
}
unique.sort();
//Now compare the array values. If there are any duplicates, throw an error
for (i = 1; i <= 9; i++) {
if (unique[i] == unique[i - 1]) {
document.getElementById('errormsg').innerHTML = 'duplicated values!';
return false;
}
}
}
There are ten of these "proj" fields (proj0 - proj9), and I have an onClick event assigned to call this function. If there are any duplicate values, the span 'errormsg' is supposed to display an error, but it's not working. What might I be missing?
//Check for duplicate project numbers
function errorCheck() {
var unique = [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
var currentValue = Number(document.getElementById('projNo' + i).value);
if(unique.indexOf(currentValue)!=-1)
{
document.getElementById('projError').innerHTML = 'duplicated values!';
return false;
}
unique[i]=currentValue;
}
return true;
}
FiddleDEMO
It first checks whether a value is already in the array by using unique.indexOf(currentValue). This function returns the index of the searched element and returns -1 if it is not found.
If it was not found, it adds it to the array and goes to the next one.
Edit:
If you want to reset the error message when you submit again and there are no more duplicates, don't forget to reset it before return true; like so:
document.getElementById('projError').innerHTML = 'no duplicates ;)';
This will detect the duplicate values :
var arr= [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
arr.push(Number(document.getElementById('proj' + i).value));
}
function dupes(arr) { // pass the array to find dupes
var i, len=arr.length, unique= [], obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
unique.push(i);
}
if(unique.length != arr.length) {
document.getElementById('errormsg').innerHTML = 'duplicated values!';
}
}
dupes(arr);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to find a math based way to find a password that makes the if statement in the below code true. I have written some stuff that brutes its way to an answer but that does not help me to understand how to solve this problem mathematically. The actual password I need to make the if statement true is irrelevant and not what I am asking for. I specifically want some code to get me started or even complete code that I can study to show me how to reverse engineer this algorithm to arrive at the answer using JavaScript.
var passed = false;
function checkPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
if (total == 248410397744610) {
passed = true;
alert(password);
}
}
Here's a simple code snippet that will do it:
function invertPass(n) {
var all = 'abcdefghijklmnopqrstuvwxyz',
out = '',
offset;
while (n > 0) {
offset = n % 17;
out = all.charAt(offset - 1) + out;
n = (n - offset) / 17;
}
return out;
}
function createPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
return total;
}
var orig = 'gdclhpdhbied',
num = createPass(orig);
console.log(invertPass(num) === orig);
Take a look at what the function actually does to total depending on its input: It multiplies by 17 and adds the position of the current char in the alphabet.
Therefore your expectedTotal (e.g. 248410397744610) will be a number divisible by 17 plus the alphabet position of the password's last letter. Use % (the modulus operator) to find said position (simply put, the number you need to subtract from expectedTotal to make it divisible by 17), then divide by 17 and repeat.