I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice"
I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers.
var rollNumber = 0;
var values = [];
function dieRolled() {
rollNumber += 1;
var numRolled = Math.ceil(Math.random() * 6);
values.push(numRolled);
document.getElementById("results").innerHTML = "";
for (var x = values.length-1 ; x>=0; x--) {
var newRoll = document.createElement("li");
newRoll.innerHTML = values [x] +"You rolled a";
document.getElementById("results").appendChild(newRoll);
if (x == 11)break;
}
}
How about this?
var output = document.getElementById("Output");
var values = [];
function roll()
{
values.push(Math.ceil(Math.random() * 6));
// If the history is too big, drop the oldest...
if (values.length > 10)
{
values.shift();
}
// Rewriting the history log
var text = "";
for (var i in values)
{
text += "You rolled a " + values[i] + "\n";
}
output.innerHTML = text;
}
// Rolling multiple times
setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>
Try this:
var list = document.getElementById('demo');
var count = 0;
function changeText2() {
count++;
if(count <= 10)
{
var numRolled = Math.ceil(Math.random() * 6);
var entry = document.createElement('li');
entry.appendChild(document.createTextNode("You rolled:"+numRolled));
list.appendChild(entry);
}
}
<input type='button' onclick='changeText2()' value='Submit' />
<p>Dices you rolled</p>
<ol id="demo"></ol>
Related
I try to get at least three responses from a total of 10 textboxes. And an alert will occur if the total number of responses is less than three. I also try to eliminate responses that are only spaces, so I use return x.replace(/^\s+|\s+$/gm,'') to get rid of spaces before and after the string.
What I need to do is first set a variable "count" to be 0. Next to detect whether there is at least one character in a specific textbox, and if so, add 1 to "count". Then do this for all 10 textboxes. After that, check whether "count" is greater than 2; if so, go to a next page; otherwise, an alert will occur.
But it didn't work.
Another question is, how can I avoid iterating the process for all 10 textboxes?
var count=0
function myTrim(x) {
return x.replace(/^\s+|\s+$/gm,'');
}
var x1 = document.getElementById("textbox1").value;
var t1 = myTrim("x1");
var n1 = t1.length;
if (n1<1){
count=count+0
} else{
count=count+1
}
var x2 = document.getElementById("textbox2").value;
var t2 = myTrim("x2");
var n2 = t2.length;
if (n2<1){
count=count+0
} else{
count=count+1
}
var x3 = document.getElementById("textbox3").value;
var t3 = myTrim("x3");
var n3 = t3.length;
if (n3<1){
count=count+0
} else{
count=count+1
}
var x4 = document.getElementById("textbox4").value;
var t4 = myTrim("x4");
var n4 = t4.length;
if (n4<1){
count=count+0
} else{
count=count+1
}
var x5 = document.getElementById("textbox5").value;
var t5 = myTrim("x5");
var n5 = t5.length;
if (n5<1){
count=count+0
} else{
count=count+1
}
var x6 = document.getElementById("textbox6").value;
var t6 = myTrim("x6");
var n6 = t6.length;
if (n6<1){
count=count+0
} else{
count=count+1
}
var x7 = document.getElementById("textbox7").value;
var t7 = myTrim("x7");
var n7 = t7.length;
if (n7<1){
count=count+0
} else{
count=count+1
}
var x8 = document.getElementById("textbox8").value;
var t8 = myTrim("x8");
var n8 = t8.length;
if (n8<1){
count=count+0
} else{
count=count+1
}
var x9 = document.getElementById("textbox9").value;
var t9 = myTrim("x9");
var n9 = t9.length;
if (n9<1){
count=count+0
} else{
count=count+1
}
var x10 = document.getElementById("textbox10").value;
var t10 = myTrim("x10");
var n10 = t10.length;
if (n10<1){
count=count+0
} else{
count=count+1
}
function checknumber() {
if (count < 3){
alert("You must enter at least 3 responses before you can continue.");
} else {
location.href="https://www.kindpng.com/imgv/hxbmxi_symbol-thumbs-up-clip-art-vector-free-clipart/" ; // if selection made, go to next page
}
}```
This screams for loops:
let count = 0;
for (let i = 1; i <= 10; i++) {
const textBoxValue = document.getElementById('textbox' + i).value;
if (textBoxValue.trim() !== '') count++;
}
With the code you have, not only the same lines are repeated 10 times (the only meaningful thing that changes there is textbox's ID), but also their values are not actually checked: with myTrim('x2') the parameter you pass inside your function is a literal string 'x2', not the value of x2 variable.
As a sidenote, always express your intent directly; if checking against an empty string, write that check as is. And yes, writing your own trim implementation is not really necessary.
In fact, you don't have to check all the textbox values:
function formHasAtLeast(requiredMinimum) {
let count = 0;
for (let i = 1; i <= 10; i++) {
const textBoxValue = document.getElementById('textbox' + i).value;
if (textBoxValue.trim() !== '') count++;
// this line will stop that iteration immediately,
// as there's no need to check for 4th, 5th etc. textbox
if (count === requiredMinimum) return true;
}
return false;
}
function checkForm() {
const minAnswers = 3;
if (formHasAtLeast(minAnswers)) {
location.href = "YOUR URL";
}
else {
alert(`You have to fill at least ${minAnswers} responses`);
}
}
You can use class selector, Document.getElementsByClassName("text-box"), first apply a common class to all such text boxes. Then loop over the results.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
You can access inputs by class name and work with result as an array:
function calculate() {
const elements = document.getElementsByClassName('value-container');
const result = Array.from(elements).map(e => e.value).filter(v => !!v && !!v.toString().trim()).length;
document.getElementById('result').innerHTML = `Count of fields with value: ${result}`;
}
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<input type="text" class="value-container" /><br/>
<button type="button" onclick="calculate()">Get Result</button>
<div id="result">
</div>
https://developer.mozilla.org/ru/docs/Web/API/Document/getElementsByClassName
https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array
Here what I have so I have a long list of check-boxes and I want to display them in text if they are check I was thinking of using the code below, but the problem I'm having is if they check and uncheck a check-box it shows up multiple times any suggestion on how to fix this?
.innerHTML += id;
If you need some more details here's a code dump of the relevant code:
Javascript
function findTotal() {
var items = new Array();
var itemCount = document.getElementsByClassName("items");
var total = 0;
var id = '';
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
if (document.getElementById(id).checked) {
total = total + parseInt(document.getElementById(id).value);
document.getElementById(id).parentNode.classList.add("active");
document.getElementById(id).parentNode.classList.remove("hover");
document.getElementById('display').innerHTML += id;
} else {
document.getElementById(id).parentNode.classList.remove("active");
document.getElementById(id).parentNode.classList.add("hover");
}
}
console.log(total);
document.getElementById('displayTotal').value = total;
}
HTML
<label class="hover topping" for="c4">
<input class="items" onclick="findTotal()" type="checkbox" name="topping" value="1.00" id="c4">BABYBEL</label>
Note: many more label classes
Previous answer should do it. Here your code (see comment "clear container"
Additionally I have simplified your code a bit. Readability greatly increased.
Maybe you should switch to jQuery in general, much simpler for your example.
var displayElement = document.getElementById('display'),
displayTotalElement = document.getElementById('displayTotal');
function findTotal() {
var items = [],
itemCount = document.getElementsByClassName("items"),
total = 0,
id = '';
// clear container
displayElement.innerHTML = "";
for (var i = 0; i < itemCount.length; i++) {
id = "c" + (i + 1);
var element = document.getElementById(id),
elementsParent = element.parentNode;
if (element.checked) {
total = total + parseInt(element.value, 10);
elementsParent.classList.add("active");
elementsParent.classList.remove("hover");
displayElement.innerHTML += id;
} else {
elementsParent.classList.remove("active");
elementsParent.classList.add("hover");
}
}
console.log(total);
displayTotalElement.value = total;
}
Reset the text before the loop:
document.getElementById('display').innerHTML = '';
At the moment you're just always adding to whatever's already thereā¦
I have a group of divs called "oponente", and if the user do not click on one of them in five seconds the script will choose one randomly. What I dont know how to do is to keep in LocalStorage which div the script had choose. Here is my script, I dont know what to write on 'key name' and so on.
$(document).ready(function () {
$(".oponente").addClass("gray");
var elements = $(".oponente");
var elementCount = elements.size();
var elementsToShow = 1;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
setTimeout(function () {
elements.eq(rand).window.localStorage.setItem('key name', 'key name');
}, 5000);
++i;
}
}
});
You can store index of selected one. Then you can get child from the parent with that index number clearly.
Let me simulate
$(document).ready(function () {
$(".oponente").addClass("gray");
var elements = $(".oponente");
var elementCount = elements.size();
var elementsToShow = 1;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
setTimeout(function () {
localStorage.setItem('indexOfSelected', selectedDiv.index());
}, 5000);
++i;
}
}
});
Then you can get the selected div with
var indexOfSelected = localStorage.getItem('indexOfSelected');
myDiv = parentDiv.children(":eq("+indexOfSelected+")")
All you need to init a selectedDiv then a parentDiv which is parent of the selectedDiv.
I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {
I followed a tutorial/modified the code to get a javascript tag cloud working in IBM Cognos (BI software). The tag cloud works fine in FireFox but in Internet Explorer I get the error:
"Message: '1' is null or not an object"
The line of code where this is present is 225 which is:
var B = b[1].toLowerCase();
I have tried many different solutions that I have seen but have been unable to get this working correctly, the rest of the code is as follows:
<script>
// JavaScript Document
// ====================================
// params that might need changin.
// DON'T forget to include a drill url in the href section below (see ###) if you want this report to be drillable
var delimit = "|";
var subdelimit = "[]"; // change this as needed (ex: Smith, Michael[]$500,000.00|)
var labelColumnNumber = 0; // first column is 0
var valueColumnNumber = 1;
var columnCount = 2; // how many columns are there in the list?
// ====================================
/*
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
*/
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
return ( num );
}
function filterNum(str) {
re = /\$|,|#|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|/g;
// remove special characters like "$" and "," etc...
return str.replace(re, "");
}
table = document.getElementById("dg");
if ( table.style.visibility != 'hidden'){ //only for visible
/*alert('Visible');*/
tags = document.getElementById("dg").getElementsByTagName("SPAN");
txt = "";
var newText = "a";
for (var i=columnCount; i<tags.length; i++) {
/*
valu = filterNum(tags[i+valueColumnNumber].innerHTML);
txt += valu;
txt += subdelimit+tags[i+labelColumnNumber].innerHTML+delimit;
i = i+columnCount;
*/
if(i%2!=0){
var newValue = filterNum(tags[i].innerHTML);
}else var newName =tags[i].innerHTML;
if((i>2) & (i%2!=0)){
newText = newText+newValue+subdelimit+newName+delimit;
if(typeof newText != 'undefined'){
txt = newText;
txt = txt.substr(9);
/* alert(txt);*/
}
}
}
}/*else alert ('Hidden');*/
function getFontSize(min,max,val) {
return Math.round((150.0*(1.0+(1.5*val-max/2)/max)));
}
function generateCloud(txt) {
//var txt = "48.1[]Google|28.1[]Yahoo!|10.5[]Live/MSN|4.9[]Ask|5[]AOL";
var logarithmic = false;
var lines = txt.split(delimit);
var min = 10000000000;
var max = 0;
for(var i=0;i<lines.length;i++) {
var line = lines[i];
var data = line.split(subdelimit);
if(data.length != 2) {
lines.splice(i,1);
continue;
}
data[0] = parseFloat(data[0]);
lines[i] = data;
if(data[0] > max)
max = data[0];
if(data[0] < min)
min = data[0];
}lines.sort(function (a,b) {
var A = a[1].toLowerCase();
var B = b[1].toLowerCase();
return A>B ? 1 : (A<B ? -1 : 0);
});
var html = "<style type='text/css'>#jscloud a:hover { text-decoration: underline; }</style> <div id='jscloud'>";
if(logarithmic) {
max = Math.log(max);
min = Math.log(min);
}
for(var i=0;i<lines.length;i++) {
var val = lines[i][0];
if(logarithmic) val = Math.log(val);
var fsize = getFontSize(min,max,val);
dollar = formatCurrency(lines[i][0]);
html += " <a href='###Some drillthrough url which includes the param "+lines[i][1]+"' style='font-size:"+fsize+"%;' title='"+dollar+"'>"+lines[i][1]+"</a> ";
}
html += "</div>";
var cloud = document.getElementById("cloud");
cloud.innerHTML = html;
var cloudhtml = document.getElementById("cloudhtml");
cloudhtml.value = html;
}
function setClass(layer,cls) {
layer.setAttribute("class",cls);
layer.setAttribute("className",cls);
}
function show(display) {
var cloud = document.getElementById("cloud");
var cloudhtml = document.getElementById("cloudhtml");if(display == "cloud") {
setClass(cloud,"visible");
setClass(cloudhtml,"hidden");
}
else if(display == "html") {
setClass(cloud,"hidden");
setClass(cloudhtml,"visible");
}
}
generateCloud(txt);
</script>
Any help or explanations is much appreciated
Sorry, I'm not seeing where a[] and b[] are defined, is this done elsewhere? Firefox and IE may be responding differently to the problem of an undefined array.