I have this Javascript/jQuery code:
for (i = 0; i < 100; i++) {
if(!(html == $("#chat-box").html()))
{
$("#chat-box").html(html);
console.log("a");
}
}
I have this iterating on a for loop 100 times. You would think that at least after the 1st time it would stop iterating unless one of the two values changed (which they don't), but it does not. I do not know why. I tried using if(htm1 != ...) and that did not work.
I believe using the text() method for your comparison will area the issue:
if(!(html == $("#chat-box").text()))
{
$("#chat-box").html(html);
}
Reason being is that jQuery processes the text to prevent issues with special characters with html(), where as with text() it returns the raw value. If it still doesn't work, console.log() out both method return values and the comparison variable to better visualize.
Your variable html is never being initialized or assigned to. What is it's value? With only the code you provided, it's value is undefined. So when you try to do this:
$("#chat-box").html(html);
What happens is this:
$("#chat-box").html(undefined);
Which has no effect. But if you were to initialize html first, it works:
var html = 'stufffff';
for (i = 0; i < 5; i++) {
if(html !== $("#chat-box").html()) {
$("#chat-box").html(html);
console.log("a");
}
}
Also, you should use !== instead of !=.
Related
I know I am very close, but I can't get the code to return anything but the 'savesTheDay' variable in the else option.I don't think I'm setting up my if....else conditionals properly. I think should be going with the "happy ending" for the if statement (in my case, the savesTheDay variable? Should I not define 'dangerLevel' inside the function since I want it to change? Thanks!
**Edited:
I am trying to get each of the phases to return when I call the assessSituation function. I can only get the saveTheDay message to return, even if the value is outside of the parameters of the condition i.e. assessSituation(1);. I'd expect to get the "Meh. Hard Pass." return value instead of saveTheDay.
Added new code, still isn't running though!**
function assessSituation (dangerLevel, saveTheDay, badExcuse) {
var saveTheDay = "Crime won't stand a chance against me!";
var dangerLevel = dangerLevel;
var badExcuse = "I'm scared, I've never gone up against this many villains";
if (10 < dangerLevel < 50) {
console.log(saveTheDay);
} else if (dangerLevel > 50) {
console.log(badExcuse);
} else
console.log("Meh. Hard Pass.");
}
JavaScript, like many other languages (C/C++, Java, etc.) except Python, does not have support for chaining comparison operators.
10 < dangerLevel < 50
is equivalent to
(10 < dangerLevel /* true or false */) < 50
(true) < 50
// or
(false) < 50
Since false == 0 and true == 1, the result will always be true since 0 and 1 are both less than 50.
To fix your logic, use the && (AND) operator:
if ((10 < dangerLevel) && (dangerLevel < 50))
I think it's only returning saveTheDay because it's the only conditional that is matched.
Your dangerLevel = 10, so dangerLevel is not > 50, and it's not smaller than 10, but it's definitely < 50. If you want another return you can change dangerLevel before if else clause.
Ps: I didn't see that your variable inside your function has the same name of the input. You should choose another name if you want to have both
If you’re passing dangerLevel into the function, you’re overwriting it when you create the dangerLevel variable inside the function. Remove “var dangerLevel = 10” and see if the output you get is what you expect.
you are setting dangerLevel = 10;
it doesn't matter what you pass in, 10 gets populated for dangerLevel, so:
10 will never be > 50
will never be <10
wil always be < 50
which is why you always get savesTheDay
You have two conflicting conditons. (dangerLevel<50) and (dangerLevel<10) so when your code runs with dangerLevel=10 its doesn't know wich one to choose. I suggest you remplace (dangerLevel<50) to (10<=dangerLevel<=50)
Basically i have to create a quiz with 3category. each with 5questions.
I would have to push the selected category-questions into this new array from the array with all the questions. I am unable to do so.
pushSelectedQuestion() {
for (var i = 0; i < this.getNumberOfQuestion; i++) {
if (usercategory == questionPool[i].category) {
mcqSelected.push(questionPool[i])
return mcqSelected;
}
}
}
usercategory = input from user.
if user chooses category 1.
if (1 == questionPool[1].category) (if it matches the category) then it will be pushed.
This is the part which i cant do
Well, from the information you've provided, there's one main issue here - the return statement is definitely shortcutting the loop - so even if you have everything else right, you'll only ever get the first matching question. The rest will have been cut out by the return statement, which stops the function and returns the value.
pushSelectedQuestion() {
for (var i = 0; i < this.getNumberOfQuestion; i++) {
if (usercategory == questionPool[i].category) {
mcqSelected.push(questionPool[i])
// the below line is causing this loop to end after the first time through the list.
// Remove it and then put a console.log(mcqSelected);
// here instead to see the value during each iteration of the loop.
return mcqSelected;
}
}
}
There are a lot of ways to accomplish what you want to do here though. For example, you could just use the javascript Array.filter method like so
let selectedQuestions = questionPool.filter(question => question.category == userCategory)
Maybe I am not understanding your question correctly, but can't you use nested arrays. If the questions are categorized beforehand that is.
I want to be able to loop over a few different labels and hide their content based on if a radio button is check or not. This is the solution I came up with, but I keep getting an error in the console.
var hazardOptions = $(".js-hazardous-option");
var hazard = $("input[name=Hazardous]");
for (var i = 0, len = hazard.length; i < len; i++) {
if (hazard[i].id === "HazardousYes" && hazard[i].checked) {
for (var ii = 0, length = hazardOptions.length; ii < length; ii++) {
hazardOptions[ii].show();
}
} else if (hazard[i].id === "HazardousNo" && hazard[i].checked) {
for (var iii = 0, leng = hazardOptions.length; iii < leng; iii++) {
hazardOptions[iii].hide();
}
}
}
The error I get is:
hide() is not a function
Not sure what I'm missing, I've tried having a look online for a similar issue, but with no luck. I'm pretty sure that the problem is here: hazardOptions[iii].hide(); but not really sure why and/or how to fix it.
When you have a list of objects from a JQuery selector, if you try to access them via index you actually get the DOM element back and not the JQuery object. It's confusing for sure but it is in the documentation.
What you effectively need to do is turn it back into a JQuery object:
$(hazardOptions[iii]).hide();
Or you can use the eq() function with does provide the JQuery object ad thus still has the hide() function:
hazardOptions.eq(iii).hide();
Most probably you need to wrap it with $
$(hazardOptions[ii]).hide()
As you currently have it, if hazard.id === "HazardousYes", you are showing all hazardOptions, and if it is "HazardousNo"you are hiding all of them.
You can call .show() and .hide() on a jQuery collection and it will apply that to all elements in the collection. The below code will replicate the logic of your original code, however, the hazardOptions final show/hide state will be solely determined by the last hazard that is checked and has an id equal to "HazardousYes" and "HazardousNo". This may be what you want, but I would imagine it's not.
var hazardOptions = $(".js-hazardous-option");
var hazards = $("input[name=Hazardous]");
hazards.each(function (index, hazard) {
if (hazard.checked) {
if (hazard.id === "HazardousYes") {
hazardOptions.show();
} else if (hazard.id === "HazardousNo") {
hazardOptions.hide();
}
}
}
Edit - Come to think of it, if you don't have elements with duplicate IDs, You can make this really simple:
hazardOptions.show($("#HazardousYes").is(":checked"));
hazardOptions.hide($("#HazardousNo").is(":checked"));
I'm iterating through a CSS keyframe in order to change the original to a new animation based on the keyframe that is closest the current behavior of the element being animated. I use the function below to obtain the keyframe rules by iterating through the stylesheets.
function findKeyframesRule(rule) {
var ss = document.styleSheets;
for (var i = 0; i < ss.length; ++i) {
for (var j = 0; j < ss[i].cssRules.length; ++j) {
if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE
&& ss[i].cssRules[j].name == rule) {
return ss[i].cssRules[j];
}
}
}
return null;
}
called like so: var keyframes = findKeyframesRule(anim);
My Problem: I need to get the length/size of ss[i].cssRules[j] (or the variable keyframes because they point to the same WebkitCSSKeyframesRule object) but have been unable to find a way to do so. I found what I think is the source for CSSKeyframesRules here, but it is in C, so I am unable to use the methods they use to find the length/size, i.e. ::length and such.
I know it has a length because I can call things like keyframes[3].keyText and get a value, so it acts like an array.
I have tried keyframes.size(), keyframes.forEach, keyframes.length, and some more attempts but they don't work because it's not an array, it's a CSSKeyframesRule object. I also attempted work arounds using the ¿parent? (I don't what to call it - I mean ss, ss[i], and ss[i].cssRules) including ss[i].cssRules.length which I thought would work but it doesn't.
Here is a fiddle to show my problem
Do any of you have any ideas?
Your code is working fine. Just try to alert
keyframes.cssRules.length
will get 5
alert(keyframes.cssRules.length);
Fiddle: http://jsfiddle.net/creativevilla/T83Nc/
I am creating a 'simple' javaScript function which basically displays new information on the page when a user clicks next or previous.
The information is taken from an array and I want to use either i++ or i-- to call an element of the array.
Heres my JavaScript:
var titles = ["Dundalk", "Navan", "Drogheda", "Dublin"];
var i = 0;
function next()
{
i++;
if (i == titles.length)
{
i = 0;
}
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
function prev()
{
if (i == 0)
{
i = titles.length;
}
i--;
var object = document.getElementById('tname');
object.innerHTML = titles[i];
}
The problem is, when I run this code in my HTML page, I get an 'UNDEFINED' result. The JavaScript is not recognizing that i has been initialized as 0 in the beginning.
If i change titles[i] to titles[2], for example, the correct text is displayed in HTML.
What am I forgetting or how can I overcome this?
Thanks
The fact that you're seeing undefined indicates that you're accessing an array index which hasn't been set. Your code looks fine at a glance, so I would guess that there's some more code you're not showing which also uses i as a loop variable and leaves it set to a value > titles.length after the code above has run.