jQuery - Making every even number in a paragraph bold - javascript

I am working on a puzzle in jQuery. I found out how to generate random numbers, but now I want to iterate over these numbers and make them bold if the number is even.
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
$("#numbers").text($("#numbers").text() + rand + " ");
}
var numbers = $("#numbers").text().split(' ');
for (var i = 0; i < numbers; i++) {
if (Number(numbers[i]) % 2 === 0) {
numbers[i] = "<span class='bold'>" + numbers[i] + "</span>";
}
}
$("#numbers").html(numbers.join(' '));
});
It seems like the bold class is not getting added to any of the elements. Any ideas why it's not working?
http://jsfiddle.net/rL3y28cm/

You need to change for loop condition to i < numbers.length, use length property to get array size
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
$("#numbers").text($("#numbers").text() + rand + " ");
}
var numbers = $("#numbers").text().split(' ');
for (var i = 0; i < numbers.length; i++) {
//------------------------^-----------
if (Number(numbers[i]) % 2 === 0) {
numbers[i] = "<span class='bold'>" + numbers[i] + "</span>";
}
}
$("#numbers").html(numbers.join(' '));
});
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>
Update : You can reduce your code and make it more simple
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
var res = [];
// array for storing the random number
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
// generating random number
res.push(rand % 2 == 0 ? "<span class='bold'>" + rand + "</span>" : rand);
// checking even or odd and wrapping by span if needed finally pushing the string to array
}
$("#numbers").html(res.join(' '));
// joining the array value and set it as html
});
.bold {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>

It is easier and more performant to generate the random number, add the span, collect all numbers (with bold or not) into a string, and apply them at once to the HTML:
$("button").on("click", function() {
var countNumbers = Number($("input[type=number]").val());
var randStr = '';
for (var i = 0; i < countNumbers; i++) {
var rand = Math.floor(Math.random() * 15000);
randStr += (rand % 2 === 0 ? "<span class='bold'>" + rand + "</span>" : rand) + ' ';
}
$("#numbers").html(randStr);
});
.bold {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" />
<button>Generate Numbers</button>
<p id="numbers"></p>

Related

javascript count present i value with previous loop output value

function myFunction() {
var text = "";
var i;
for (i = 0; i <= 10; i++) {
text += + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I want to add present i value into previous loop output value. This maybe a simple question. I have searched in google and stackoverflow. But, didn't get the desired result.
In above screenshot,
0 is the previous loop value + 1 is present i returns => 1
1 is the previous loop value + 2 is present i returns => 3
3 is the previous loop value + 3 is present i returns => 6
6 is the previous loop value + 4 is present i returns => 10
You need another persistent variable that keeps track of the last total that was concatenated with text:
function myFunction() {
var text = "";
var i;
var lastTotal = 0;
for (i = 0; i <= 10; i++) {
var newTotal = lastTotal + i;
text += + newTotal + "<br>";
lastTotal = newTotal;
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
(technically, you don't need the newTotal variable, but it makes the code's intent more clear)
You could also do this a bit more elegantly with reduce:
function myFunction() {
let text = '';
Array.from({ length: 11 }, (_, i) => i)
.reduce((lastTotal, i) => {
const newTotal = lastTotal + i;
text += newTotal + '<br>';
return newTotal;
}, 0);
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You just need a second variable to hold the last value:
function myFunction() {
var text = "";
var sum = 0;
for (var i = 0; i <= 10; i++) {
sum += i;
text += sum + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
Keep a count of the last number:
function myFunction() {
var text = "";
var i;
var count = 0;
for (i = 0; i <= 10; i++) {
count += i;
text += count + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
You can use the function reduce to fill the operations and then use the function forEach to build the desired output.
function myFunction() {
var html = "";
Array.from({length: 10}, (_, i) => i + 1).reduce((a, c, i) => {
a[i] = (a[i - 1] || 0) + c;
return a;
}, []).forEach((n, i, arr) =>
(html += (arr[i - 1] || 0) + " + " + (i + 1) + " = " + n + "<br>"));
document.getElementById("demo").innerHTML = html;
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>
I think I'd just use an array so that you both have the previous sum, and can also use it with .join() for setting the HTML.
function myFunction() {
for (var i = 0, a = []; i <= 10; i++) {
a[i] = i + (a[i-1] || 0);
}
document.getElementById("demo").innerHTML = a.join("<br>");
}
<button onclick="myFunction()">Count</button>
<p id="demo"></p>

Count amount of times a value is represented

i have some code that takes input numbers and put them into a new array. How can i make it so my alert tells the user how many times the number is represented in the input? Exampel 0,4,4,2,3,4,1 would show "0 appears 1 time, 4 appears 3 times" and so on...I think im close but cant get the final part right...
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count = 0;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === parseInt(input)) {
count++;
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
I have changed your showTxt function
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count;
for (var i = 0; i < newArray.length; i++) {
count = 0;
for (var j = 0; j < newArray.length; j++) {
if (newArray[i] === newArray[j]) {
count++;
}
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
You could use the method from this gist like so:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.replace(/ /g, '').split(",").sort();
compressArray(split);
}
function compressArray(original) {
var compressed = [];
// make a copy of the input array
var copy = original.slice(0);
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (original[i] == copy[w]) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i];
a.count = myCount;
compressed.push(a);
}
}
for (var i = 0; i < compressed.length; i++) {
var message = compressed[i].value + ' appears ' + compressed[i].count + ' times.';
alert(message);
document.getElementById("print").innerHTML += message + '</br>';
}
};
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
Check this out, may be it'll helpful .
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
let countedValues = newArray.reduce(function(obj,val){
if(obj[val])
obj[val] += 1;
else
obj[val] = 1;
return obj
}, {})
for (let value in countedValues ) {
alert("Number " + value + " appears " + countedValues[value] + " times");
}
text = newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

Is it possible to add weight to images in a generator?

I wish to make a random image generator (which is working fine), however, I was wondering is there a way to add weight to certain images which won't appear as much as others?
I have attached the code below:
<script language="JavaScript">
function random_imglink(){
var myimages=new Array()
myimages[1]="Blue_Car.png"
myimages[2]="Red_Car.png"
myimages[3]="White_Car.png"
myimages[4]="Black_Car.png"
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
function confirmRefresh() {
var okToRefresh = confirm("Do you really want to refresh the page?");
if (okToRefresh)
{
setTimeout("location.reload(true);",10);
}
}
</script>
<input type="button" value="Generate a new player" onClick="document.location.reload(true)">
</script>
</a></p>
I do have a SMALL amount of knowledge regarding JavaScript, however, I'm no pro.
var myimages=new Array();
myimages[0]="Blue_Car.png";
myimages[1]="Red_Car.png";
myimages[2]="White_Car.png";
myimages[3]="Black_Car.png";
// myimages[4] = ...
// All values summed up must equal 1
var probabilities=new Array();
probabilities[0]=0.1; // 10%
probabilities[1]=0.1; // 10%
probabilities[2]=0.25; // 25%
probabilities[3]=0.55; // 55%
// probabilities[4] = ... (also need to change the other probability values)
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for(var i=0; i < probabilities.length; i++) {
probabilitiy_sum += probabilities[i];
if(rand <= probabilitiy_sum ) {
return myimages[i];
}
}
return myimages[myimages.length];
}
// Just for testing:
for(var i=0; i < 10; i++) {
document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
<div id="textbox"></div>
To extend #ByteHamster's response (accept his, not mine), you can do the same thing with an array of objects to easier keep track of the possibilities.
var myimages = [{
image: "Blue_Car.png",
probability: 0.1
}, {
image: "Red_Car.png",
probability: 0.1
}, {
image: "White_Car.png",
probability: 0.25
}, {
image: "Black_Car.png",
probability: 0.55
}];
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for (var i = 0; i < myimages.length; i++) {
probabilitiy_sum += myimages[i].probability;
if (rand <= probabilitiy_sum) {
return myimages[i].image;
}
}
return myimages[myimages.length].image;
}
// Just for testing:
for (var i = 0; i < 10; i++) {
document.getElementById("textbox").innerHTML += getImage() + "<br />";
}
<div id="textbox"></div>
Easy way would just to be to increase the length of your array, and then add the images with more probability to hit more times, and the images with less probability less times. You can use a for loop for each.
for (i=0;i<15;i++) {
myimages[i] = "Blue_Car.png";
}
for (i=15;i<40;i++) {
myimages[i] = "Red_Car.png";
}
for (i=40;i<80;i++) {
myimages[i] = "White_Car.png";
}
for (i=80;i<100;i++) {
myimages[i] = "Black_Car.png";
}
You already have an answer, but I'll post mine anyway.
<script language="JavaScript">
var counter = 0; // this is just to show that something happens when you randomly get the same car as the previous car.
function random_imglink() {
var myimages = [
{weight: 3, url: "http://insideevs.com/wp-content/uploads/2012/07/bollare-bluecar.jpg"}, // blue
{weight: 10, url: "http://4.bp.blogspot.com/-UKeEILt_8nw/UZOCIEMrMVI/AAAAAAAAAvI/X5i-HaJRnTc/s400/red+car10.jpg"}, // red
{weight: 5, url: "http://i.telegraph.co.uk/multimedia/archive/02661/Audi-A5-Sportback_2661284b.jpg"}, // white
{weight: 2, url: "http://1.bp.blogspot.com/-mojnxHJlWVA/UZ1KShiKMeI/AAAAAAAAHMo/oO7qMo7PJq4/s400/Best-Black-Car-2009_j2bq.gif"} // black
];
// calculate total weigt
// this example: totalWeight = 20
// Then we search a random number from 0 to 19. 0,1,2 belongs to blue; 3 to 12 is red; 13 to 17 is white; 18 to 19 is black
// we add min and max range to the image object, so we can easily return the good one.
var totalWeight = 0;
for (var i=0; i<myimages.length; i++) {
myimages[i].min = totalWeight;
myimages[i].max = totalWeight + myimages[i].weight - 1; // example: if the first weight is 3; the max is 3-1 = 2
totalWeight += myimages[i].weight;
}
var ry = Math.floor(Math.random() * totalWeight);
for (var i=0; i<myimages.length; i++) {
if (ry >= myimages[i].min && ry <= myimages[i].max) {
var index = i; // we've got a winner
break;
}
}
document.getElementById('image').innerHTML = '<img src="' + myimages[index].url + '">';
document.getElementById('counter').innerHTML = counter++;
}
window.onload = function() {
random_imglink();
}
</script>
<input type="button" value="New random car" onClick="random_imglink()">
<div id="counter"></div>
<div id="image"></div>

Evaluating specific array value using jQuery or JavaScript

I have 160 inputs in my page. I want to add every 8 inputs and output it elsewhere. Instead of manually using
var total1 = inputVals[0] + inputVals[1] + inputVals[2] + inputVals[3] + inputVals[4] + inputVals[5] + inputVals[6] + inputVals[7] + inputVals[8];
I want a function with which you can just specify the starting and ending index like addarray(9, 17) and it will add all the values between and will return it. I prefer the function to be in javascript but jquery is OK.
Suppose you have <input> elements defined as:
<input type="text" class="myInput" />
<input type="text" class="myInput" />
<input type="text" class="myInput" />
...
You can create a method that does the job with the help of jQuery:
function add(start, end) {
var total = 0;
$(".myInput").slice(start, end).each(function() {
total += +this.value;
});
return total;
}
The same method in pure JavaScript will look like:
function add(start, end) {
var total = 0,
inputs = document.getElementsByClassName("myInput");
for (var i = start; i < Math.min(end, inputs.length); i++) [
total += +inputs[i].value;
});
return total;
}
Try
function calcTotal(index) {
var total = 0;
for (var i = 0; i < 9; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcTotal(0);
OR
function calcRangeTotal(index, count) {
var total = 0;
for (var i = 0; i < count; i++) {
total += inputVals[index + i];
}
return total;
}
var total1 = calcRangeTotal(0, 9);
Look at this:
var calculate = function() {
var sum=0;
$("input").each(function(index,element){
sum+=Number($(element).val());
});
alert(sum);
};
$(function(){
$("button").on("click",calculate);
});
Here is th jsFiddle.
var sum = 0;
function caluculate(firstIndex,secondIndex){
for(var i=one;i<secondIndex;i+=8)
sum=parseInt(sum+inputVals[i]);
}
function addarray($start,$end) {
var total = 0;
for(var i = $start; i < $end; i++)
total += inputVals[i];
return total;
}
var myTotal = addarray(9,17);

Categories

Resources