I'm trying to replace the text content of two divs ("city" and "budget"), one with a random US city from an array and one with a randomly generated number. The code works fine when I run it in the console, but for some reason it won't display in the browser. Any idea what's going wrong here? For my purposes I'm not using JQuery, just straight JavaScript.
HTML:
<div id="result">
<div class="city">
<h1>City</h1>
</div>
<div class="budget">
<h1>Budget</h1>
</div>
</div>
JS
function city() {
document.getElementsByClassName('.city').innerText = usCities[Math.floor(Math.random() * usCities.length)];
}
function budget() {
document.getElementsByClassName('.budget').innerText = Math.floor(Math.random() * 1000000) + 100000;
}
The problems are:
You doesn't give [0] to getElementsByClassName.
Using . in the paremeter of getElementsByClassName.
You doesn't call the function
You doesn't define the usCities
This should works:
let usCities = ["Chicago", "New York"]
function city() {
document.getElementsByClassName('city')[0].innerText = usCities[Math.floor(Math.random() * usCities.length)];
}
function budget() {
document.getElementsByClassName('budget')[0].innerText = Math.floor(Math.random() * 1000000) + 100000;
}
city();
budget();
<div id="result">
<div class="city">
<h1>City</h1>
</div>
<div class="budget">
<h1>Budget</h1>
</div>
</div>
Related
I am currently trying to loop through multiple input boxes using loops but I don't know how to go about doing it.
My JS code:
function tagger() {
var t;
for (t = 0; t < 5; t++) {
document.getElementsByClassName("pl")[0].getElementsByTagName("input")
}
};
return tagger();
HTML:
<h1 class="pizza">Pineapple</h1>
<body class="maco">
<div class="keys">
<span class="press" onclick="car()"><i class="fas fa-fingerprint"></i><h2>Log In</h2></span>
<span class="type" id="heyu"><input class="entry" placeholder="Password"></span>
</div>
</body>
</html>
Thanks in advance for any help rendered!
You must to add the t variable as index of (getElementsByTagName)
document.getElementsByClassName("pl")[0].getElementsByTagName("input")[t];
or you can use forEach Method is the best way for looping trough arrays
function tragger () {
var _Element = Array.from(document.querySelector("pl input"));
_Element.forEach(function (ele) {
//do some code for each input
ele.value = 'etc';
});
}
tragger();
I'm a hobbyist coder and I'm working on a side project. I want the "Random" coding at the bottom of this list of variables (which functions as an ...Array right?) to randomly select specifically from each set of variables. How do I make this work?
var flanks = [
"Androxus-Flank",
"Zhin-Flank",
"Buck-Flank",
"Evie-Flank",
"Lex-Flank",
"Maeve-Flank",
"Skye-Flank",
"Talus-Flank"
];
var frontline = [
"Ash-Frontline",
"Barik-Frontline",
"Fernando-Frontline",
"Inara-Frontline",
"Makoa-Frontline",
"Torvald-Frontline",
"Ruckus-Frontline"
];
var damage = [
"Bomb King-Damage",
"Tyra-Damage",
"Viktor-Damage",
"Willo-Damage",
"Kinessa-Damage",
"Lian-Damage",
"Sha Lin-Damage",
"Strix-Damage",
"Cassie-Damage",
"Drogoz-Damage"
];
var support = [
"Grohk-Support",
"Grover-Support",
"Mal'Damba-Support",
"Pip-Support",
"Jenos-Support",
"Seris-Support",
"Ying-Support"
];
$("#button").click(function() {
$("#flanks").text(flanks[Math.floor(Math.random() * flanks.8)]);
$("#frontline").text(frontline[Math.floor(Math.random() * frontline.7)]);
$("#damage").text(damage[Math.floor(Math.random() * damage.10)]);
$("#support").text(support[Math.floor(Math.random() * support.7)]);
});
and this is the html I'm building alongside it; if anyone wouldn't mind proofreading.
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Basic Functioning Demo for 'The Unofficial Hi-Rez Paladins' Champion Roulette'
</div>
<div class="panel-body">
<ul>
<li><strong>Flank</strong>--<span id="flanks"></span></li>
<li><strong>Frontline</strong>--<span id="frontline"></span></li>
<li><strong>Damage</strong>--<span id=damage></span></li>
<li><strong>Support</strong>--<span id="support"></span></li>
</ul>
</div>
<div class="panel-footer">
R o l l
</div>
</div>
</div>
<img src="https://i.imgur.com/u9nFQuH.png" class="center"/>
This should work if you just refer to the correct arrays
For example:
$("#race").text(races[Math.round((Math.random() * 32))]);
There is no races array
try changing races to flank
$("#race").text(flank[Math.round((Math.random() * 32))]);
An easy way to see if this is working is to use console logs
console.log(flank[Math.round((Math.random() * 32))]);
How do I make this work?
Change the multiplier to array's (race in this case) length and Math.round with Math.floor so that you don't get undefined
$( "#race" ).text( races[ Math.floor( Math.random() * races.length ) ] );
I need to a get a random string from the objects inside an array when you click the button. But for some reason my code is not executing.
var quotes = [{
quote: "Quote1",
source: "Source1"
},
{
quote: "Quote2",
source: "Source2"
},
{
quote: "Quote3",
source: "Source3"
},
{
quote: "Quote4",
source: "Source4"
},
{
quote: "Quote5",
source: "Source5"
}
];
function getRandomquote() {
var randomindex = Math.floor(Math.random() * (quotes.length));
var quotesarr = quotes[randomindex];
var objquote = quotesarr.quote;
var objsource = quotesarr.source;
document.getElementById("quote").innerHTML = objquote;
document.getElementById("source").innerHTML = objsource;
}
function printQuote() {
document.getElementById("loadQuote").onclick = getRandomquote;
}
printQuote();
<div class="container">
<div id="quote-box">
<p class="quote"> hello</p>
<p class="source"> hello</p>
</div>
<button id="loadQuote" onclick="printQuote();">Show another quote</button>
I am getting this error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null
at HTMLButtonElement.getRandomquote (randomtest1.js:27)
Update after answers below
I changed getElementById to getElementsByClassName, and now there are no error messages.
But when I click the button, it does not change the elements. I believe I have made a mistake on the printQuote function. I cannot figure it out.
You'll need to add the ids to the elements as below. Or use getElementsByClassName() or use querySelector(".quote").
var objquote = "Hello";
var objsource = "World";
document.getElementById("quote").innerHTML=objquote;
document.getElementById("source").innerHTML=objsource;
<div id="quote-box">
<p id="quote" class="quote"> hello</p>
<p id="source" class="source"> hello</p>
</div>
You can't use getElementById to retrieve an element by its class. You'll need to specify an id or use getElementsByClassName- https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName
var els = document.getElementsByClassName('test')
console.log(els.length)
<div class="test"></div>
In your example:
<p class="quote" id="quote"> hello</p>
<p class="source" id="source"> hello</p>
Please find the working code below. i have removed unwanted functions.
html
<div id="quote-box">
<p class="quote">hello</p>
<p class="source">hello</p>
</div>
<button id="loadQuote" onclick="getRandomquote();">Show another quote</button>
js
var quotes=[
{quote:"Quote1", source:"Source1"},
{quote:"Quote2", source:"Source2"},
{quote:"Quote3", source:"Source3"},
{quote:"Quote4", source:"Source4"},
{quote:"Quote5", source:"Source5"}
];
getRandomquote=function(){
var randomindex=Math.floor(Math.random()*(quotes.length));
var quotesarr=quotes[randomindex];
document.getElementsByClassName("quote")[0].innerHTML=quotesarr.quote;
document.getElementsByClassName("source")[0].innerHTML=quotesarr.source;
}
you have not set id in your p tag ...please set id='quote' and it should start working.
I changed getElementById to getElementsByClassName, and now there are no error messages.
But when I click the button, it does not change the elements. I believe I have made a mistake on the printQuote function. I cannot figure it out.
I am creating ListView using my template:
HTML:
<div id="ItemTemplate" data-win-control="WinJS.Binding.Template">
<div class="ItemTemplate">
<div class="back"></div>
<div data-win-bind="innerText:Info.shortName" class="shortName"></div>
<div data-win-bind="innerText:value Converters.BeginValue" class="value"></div>
<div data-win-bind="innerText:value Converters.EndValue" class="valueEnd"></div>
<div data-win-bind="innerText:Info.longName"></div>
<img data-win-bind="src:Info.flag" class="flag" />
<div data-win-bind="innerText:change Converters.BeginChange" class="change"></div>
<div data-win-bind="innerText:change Converters.EndValue" class="changeEnd"></div>
<div data-win-bind="innerText:changePercent Converters.BeginChangePercent" class="changePercent"></div>
<div data-win-bind="innerText:changePercent Converters.EndValue" class="changePercentEnd"></div>
</div>
</div>
The issue is when I meet the very long name I need to adjust font-size.
So I do (for each element in list):
JavaScript:
template = document.getElementById('ItemTemplate');
// Adjust font - size
var name = item.data.Info.longName;
// Split by words
var parts = name.split(' ');
// Count words
var count = parts.filter(function(value) {
return value !== undefined;
}).length;
var longNameDiv = $(template).children("div").children("div").eq(4);
if (count > 2) {
// Display very long names correctly
$(longNameDiv).removeClass();
$(longNameDiv).addClass("veryLongName");
}
var rootDiv = document.createElement('div');
template.winControl.render(item.data, rootDiv);
return rootDiv;
CSS:
.veryLongName {
font-size: 10pt;
}
But it doesn't effect selectivly. Moreover seems like it is check conditions for the first time and then just apply the same setting for remaining items. But it needs to change font-size to smaller only in case if the name is too long. So what am I doing wrong? Thanks.
Try by using following code instead, but u must include jquery for it.
jsfiddle : http://jsfiddle.net/vH6G8/
You can do this using jquery's filter
$(".ItemTemplate > div").filter(function(){
return ($(this).text().length > 5);
}).addClass('more_than5');
$(".ItemTemplate > div").filter(function(){
return ($(this).text().length > 10);
}).removeClass('more_than5').addClass('more_than10');
DEMO
I do not have a good grasp of the js namespace and am WAGing* re the title, but that's one of my guesses about what's happening.
WAG = Wild Guess
My app is crashing (dramatically); trying to figure out why. In fact, after 3 Q/A pairs, it blows up the entire Chrome tab..! I'm beginning to suspect I've done something wrong in my code...
Warning: Save your browsing session before running these jsFiddles. (In Chrome, the jsFiddle only blows up its own tab but I can't comment on other browsers)
jsFiddle One
jsFiddle Two - dupe in case jsFiddle One blown away
Please help me to understand exactly which spectacular moronism I've committed today.
HTML:
<div id="result">
<div class="truth tr0"><h2>---</h2></div>
<div class="truth tr1"><h2>answer to one</h2></div>
<div class="truth tr2"><h2>answer to two</h2></div>
<div class="truth tr3"><h2>answer to three</h2></div>
<div class="truth tr4"><h2>answer to four</h2></div>
</div>
<div id="replaceLink">
<div class="youcould yc1">
<h2>QUESTION ONE</h2>
</div>
<div class="youcould yc2">
<h2>QUESTION TWO</h2>
</div>
<div class="youcould yc3">
<h2>QUESTION THREE</h2>
</div>
<div class="youcould yc4">
<h2>QUESTION FOUR</h2>
</div>
<div class="youcould yc5">
<h2>THANK YOU</h2>
</div>
</div>
<div id="response"></div>
<input type="button" id="mybutt" value="Start Test" />
Javascript/jQuery:
var cnt = 0;
var window = {};
window.arrDone = [];
function nextQues() {
if (window.arrDone.length == 4) return 5;
success = 0;
while (success == 0) {
nn = Math.floor(Math.random() * 3) + 1;
if (window.arrDone.indexOf(nn) == -1 && nn != 5) {
success++;
window.arrDone.push(nn);
}
}
return nn;
}
$('.youcould, .truth').hide();
$('.tr0').show();
$('.youcould').click(function() {
$(this).hide();
thisA = window.arrDone[window.arrDone.length -1];
$('.tr'+thisA).show();
});
$('.truth').click(function() {
$(this).hide();
nextQ = nextQues();
$('.yc'+nextQ).show();
});
$('#mybutt').click(function () {
$(this).hide();
$('.tr0').hide();
nextQ = nextQues();
$('.yc'+nextQ).show();
});
My guess would be
var window = {};
window is special, so creating a global variable named window is begging for trouble.
Your while loop runs infinitely on the third pass because it doesn't meet the condition.
At some point, arrDone will contain the numbers 1, 2, and 3, as produced by your random generator (which will never produce 5, btw). In that case, nextQues() does not abort and return five (as arrDone.lenght == 3), and will enter the loop. Your random generator produces nothing but the numbers 1, 2, and 3, which always are already in the array, so the if-condition (that would end the loop) is never fulfilled. You have an infinite loop generating random numbers.
I guess you want
function nextQues() {
var l = 4;
if (window.arrDone.length >= l)
return l+1;
while (true) {
var nn = Math.floor(Math.random() * l) + 1; // generate 1, 2, 3 or 4
if (window.arrDone.indexOf(nn) == -1) {
window.arrDone.push(nn);
return nn;
}
}
}