Trying to solve the fizzbuzz problem in javascript with a little html. I want to put the answers in a <ul> and display them on the page. To do this, I need to take the fizz-buzz's and somehow add them in a <li> element to the UL, with a prepend or append in jQuery. My code runs fine, until I add jQuery to the equation to prepend the <li>s into the html. I currently have the numbers/fizz-buzzes popping up with alerts.
I have tried putting in $(document).ready(function() {}, wrapping all javascript inside brackets. If I do, it breaks, even if there is 0 jQuery actually in the javascript section. Simply breaks, as if the page is never actually ready and thus the javascript will never run.
Assuming I can get any jQuery in to work, can I simply put jQuery statemments inside of my elseif statements?
example:
else if (n1 % 5 === 0) {
$("ul").prepend("<li>n1</li>")
}
Javascript:
var number = prompt("number?");
var num_int = parseInt(number);
var smack = new Array(num_int);
//populating array with numbers 1 through num_int
for (i = 0; i < smack.length; i++) {
smack[i] = i+1;
} //test again still working?
smack.forEach(function(n1) { //going through each array element, checking for fizz/buzz
if (n1 % 3 === 0 && n1 % 5 === 0) {
alert("fizz-buzz")
}
else if (n1 % 3 === 0) {
alert("fizz")
}
else if (n1 % 5 === 0) {
alert("buzz")
}
else {
alert(n1)
}
}); //end of forEach
HTML:
<hmtl>
<head>
<script src="scripts.js"></script>
<script src="jquery-1.11.2.js"></script>
</head>
<body>
<p>
<h1>Fizzbuzz</h1>
<ul id="hard">
<li>test</li>
</ul>
</p>
</body>
</html>
JSFiddle
Thanks in advance for any help! I'm sure this is a ridiculously easy question for anyone who has experience. I'm just getting into it, and while the math/logic section of fizzbuzz was pretty straightforward, getting it to display correctly is killing me.
You should load jquery before your script.js
Here's a demo
I added $('#hard').append
Changing the JQuery part to:
var number = prompt("number?");
var num_int = parseInt(number);
var smack = new Array(num_int);
//populating array with numbers 1 through num_int
for (i = 0; i < smack.length; i++) {
smack[i] = i+1;
} //test again still working?
smack.forEach(function(n1) { //going through each array element, checking for fizz/buzz
if (n1 % 3 === 0 && n1 % 5 === 0) {
$('#hard').append("<li>fizz-buzz</li>");
}
else if (n1 % 3 === 0) {
$('#hard').append("<li>fizz</li>");
}
else if (n1 % 5 === 0) {
$('#hard').append("<li>buzz</li>");
}
else {
$('#hard').append("<li>"+n1+"</li>");
}
}); //end of forEach
would help.
The changes here is inside the if conditions. You append your li to the ul each time and you will have your answers in the list.
Hope this helped.
Related
Would anyone be so kind as to advise me how to amend this JavaScript please? I'll admit I don't have much experience working with JavaScript and I've tried myself but ended up a bit lost.
To explain, WooCommerce outputs products on my site in .columns-3 and .columns-4, and assigns .first and .last classes accordingly.
If the site is loaded on mobile, the script below will remove the .first and .last tags, and re-assign them to display the products in two columns.
The script currently only targets .columns-3 within function defaultProductRows and function adjustProductRows. I need to also target .columns 4 within the same script, but I'm not sure how to go about adding it.
<script>
$(window).on('load resize', function (){
var windowWidth = $(window).width();
if(windowWidth < 753){ // this is my screen size break point for the rows
adjustProductRows(); // call the function to adjust add last and first classes
} else {
defaultProductRows(); // else if large screen size then get everything back to defalut
}
});
function defaultProductRows(){
var products = $('ul.products.columns-3 li.type-product');
products.each(function(idx, li) {
var product = $(li);
// remove all classes we added
$('ul.products li.adjusted-row.first').removeClass('adjusted-row first');
$('ul.products li.adjusted-row.last').removeClass('adjusted-row last');
if(idx == 0) { // make sure first li tag gets first class
product.addClass('first');
}
else if((idx+1) % 3 == 0) //this will make sure we have 3 rows by adding last classes after each 3 products
{
product.addClass('last');
}
else if(idx % 3 == 0)
{
product.addClass('first'); // make sure all products divided by 3 will have first class
}
else
{
console.log(idx); // just checking for the index
}
});
}
function adjustProductRows() {
var products = $('ul.products.columns-3 li.type-product');
products.each(function(idx, li) {
var product = $(li);
if(idx % 2 == 0) // we are even
{
product.addClass('adjusted-row first');
product.removeClass('last');
}
else // we are odd
{
product.addClass('adjusted-row last');
product.removeClass('first');
}
});
}</script>
Change your selector to include columns-4
From:
var products = $('ul.products.columns-3 li.type-product');
To:
var products = $('ul.products.columns-3 li.type-product, ul.products.columns-4 li.type-product');
This tells jQuery to select li.type-products that are part of either columns-3 or columns-4
I wrote a JavaScript function that takes the current number of spans of the class mini in the paragraph element with an id mega, which is at least 1, and if there are less than 4, adds enough to make 4. If there was no second mini, then the second mini, which the function should create, should say 2nd, if a third one is created, it should say 3rd, and if a fourth is created, it should say 4th. For example, if there are already 2 mini spans, the program, should add 2 more, the first one added saying 3rd and the second one saying 4rd. Here's the code:
function addSpans(currentNumOfSpans)
{
var mega = document.getElementById("mega");
var mini = document.createElement("span");
mini.className = "mini";
if (currentNumOfSpans < 4)
{
if (currentNumOfSpans < 3)
{
if (currentNumOfSpans < 2)
{
mini.innerHTML = "2<sup>nd</sup>;
mega.appendChild(mini);
}
mini.innerHTML = "3<sup>rd</sup>;
mega.appendChild(mini);
}
mini.innerHTML = "4<sup>th</sup>;
mega.appendChild(mini);
}
}
Soooo.... If currentNumOfSpans is 3, it works fine, and adds 4th to mega. However, if currentNumOfSpans is 1 or 2, while it should add 2nd3rd4th or 3rd4th, respectively, it just adds 4th. Can someone help me figure out what's wrong with this. Any help's appreciated, thanks!
Note: If you notice any typos, please comment or edit, but they aren't the problem, I've checked over my code in a syntax checker, but I often make errors in my code on SO because I use a tiny phone keyboard. So basically, typo's, whichI probably made, aren't the real problem. Thanks!
Your example included a few typos, most of which could be found by running your code through a debugger, like http://jshint.com.
However, I would use a more functional approach. The following method is not hard coded like yours, so you could use it for multiple elements, or use a different number of spans with very minimal changes to the usage, I've shown this in the demo below.
function getSuffix(i) {
var j = i % 10, k = i % 100;
if (j == 1 && k != 11) return i + "<sup>st</sup>";
if (j == 2 && k != 12) return i + "<sup>nd</sup>";
if (j == 3 && k != 13) return i + "<sup>rd</sup>";
return i + "<sup>th</sup>";
}
function addSpans(scope, length) {
var spans = scope.querySelectorAll('.mini');
var current = length - (length - spans.length);
while(current < length) {
var span = document.createElement('span');
span.className = 'mini';
span.innerHTML = getSuffix(++current);
scope.appendChild(span);
}
}
var wrap = document.querySelector('.wrap'), divs;
var clone = wrap.cloneNode(true);
wrap.parentNode.appendChild(clone);
divs = wrap.querySelectorAll('.mega');
for(var i in Object.keys(divs)) addSpans(divs[i], 4);
divs = clone.querySelectorAll('.mega');
for(var i in Object.keys(divs)) addSpans(divs[i], 6 + (i * 2));
.mega { font-size: 0; } .mini { display: inline-block; width: 40px; font-size: 16px; }
<div class="wrap">
<div class="mega"></div>
<div class="mega"><span class="mini">1<sup>st</sup></span></div>
<div class="mega"><span class="mini">1<sup>st</sup></span><span class="mini">2<sup>nd</sup></span></div>
<div class="mega"><span class="mini">1<sup>st</sup></span><span class="mini">2<sup>nd</sup></span><span class="mini">3<sup>rd</sup></span></div>
<div class="mega"><span class="mini">1<sup>st</sup></span><span class="mini">2<sup>nd</sup></span><span class="mini">3<sup>rd</sup></span><span class="mini">4<sup>th</sup></span></div>
</div>
I am learning javascript in codecademy and so far I understand how alot of things work. Sadly they dont explain how to target an elements color or how to target elements / selectors / divs.
I am testing out my knowledge. What I am trying is to give every second list item the color red by using the for loop.
How do I do this?
var listColor = function(){
var color = style.("red");
var list = getElementsByTagName("li");
for (i = 0; i < list.length; i + 2;) {
list === color
}
];
listColor();
and here my http://jsfiddle.net/Lr8nZ/15/
UPDATED JSfiddle but still not working http://jsfiddle.net/Lr8nZ/23/
so basically:
Red,
Black,
Red,
Black
Something do like this.
var listColor = function(){
var list = document.getElementsByTagName("li");
for (i = 0; i < list.length; i++) {
if(i%2==0)
list[i].style="color:red";
else
list[i].style="color:blue";
}
}
listColor();
You have a few syntax errors, but you can do this:
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i++) {
if (i % 2 === 0) {
list[i].style.color = 'red';
}
}
};
// Or...
var listColor = function() {
var list = document.getElementsByTagName('li');
for (var i = 0, l = list.length; i < l; i += 2) {
list[i + 1].style.color = 'red';
}
};
listColor();
When you increment i make sure you're updating its value with i++ or i += 1, or you'll create an endless loop.
i % 2 uses the % modulus operator. It's the remainder you would get from dividing the two numbers. Even numbers divide evenly by 2, so the remainder will be 0, which we check for.
The property you were looking for is called style. It has a property called color which we set to the string 'red' in this case.
try this
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
index=1;
$("#temp li").each(function(){
if(index%2==0)
{
$(this).css("color","red")
}
index++;
});
})
</script>
<style>
</style>
</head>
<body>
<ul id='temp'>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>
</body>
</html>
Try using a console to see the errors in your code. It's a tool that's indispensible for any js coder. Here's the updated fiddle http://jsfiddle.net/Lr8nZ/24/
The first thing which you notice is style.color('red'). For this line to be even valid js, there has to be a style object defined. Otherwise it will search for it on window which always leads to confusion.
Another thing is note how we have to actually assign the new value to i in for loop' third condition. Just mentioning i+2 will not work because i will stay the same resulting in an infinite loop.
Again, fire up web console. Generally, you do that by right clicking on page > Inspect > Web console.
I have 5 div tags with the same class. Each div tag has a textbox and a dropdownlist with numbers.
How can I check if all these div tags' textboxes and dropdownlists are empty or not and if it is "do something".
$step is an array with all of my div tags.
var $step = $(".wizard-step2:visible");
My Textbox have a class Comment and my Dropdownlist have a class Grade.
I have coded this so far but its wrong, I dont want it to check on each div tag, I want it to check all of them.
This is the code that is wrong:
var Comment = $step.find(".Comment").val();
var Grade = $step.find(".Grade").val();
for (var i = 0; i < $step.length; i++) {
if (Comment != null && Grade > 0) { {
// do this
}
} else {
alert("You must enter both fields");
}
}
EDIT:
I think that I did not explain my question well, my code works like all of the answers I got on this question. I dont want to make this if statement to check each div tag. I want to be able to check if all of the div tags have any empty fields do something " else if all the div tags fields are filled do something.
Users are allowed to leave the fields empty, but if all of the div tags fields are filled do something.
I do not want to do a if statement for each div tag, I want to do a if statement if all the div tags have any empty fields or if all are field.
Lets say I have 5 div tags. I have filled 4 of them and when I filled the last one 5 div tags are filled. Here I want this " do something ", else nothing should happen. I dont want the if statements to be executed on div tag 1, 2, 3, 4 that are filled I want the if statement to happen when the 5th is filled beacuse then all the div tags are filled else nothing should happen
Find the filled elements of each class, and use the length of the resulting selections to perform your tests:
var $step = $(".wizard-step2:visible");
// returns true if the element's value is not null
function filled() {
return !!this.value;
}
// count the number of non-empty elements
var n_step = $step.length;
var n_comments = $step.find('.Comment').filter(filled).length;
var n_grades = $step.find('.Grade' ).filter(filled).length;
if (n_comments === n_step && n_grades === n_step) {
// all filled
} else if (n_comments === 0 && n_grades === 0) {
// all empty
} else {
// mixed - do nothing
}
Something like this:
$(".wizard-step2:visible").each(function(){
var Comment = $(this).find(".Comment").val();
var Grade = $(this).find(".Grade").val();
if (Comment != '' && Grade > 0) {
{
// do this
} else {
alert("You must enter both fields");
}
});
You can iterate over a collection or array like this:
$(".wizard-step2:visible").each(function(count){
var isCommentEmpty = $(this).find(".comment").val().length == 0;
if(isCommentEmpty){
alert('Comment on div ' + count + ' is empty!';
}
});
try to get your comment inside of each something like
var bOK, Comment, Grade ;
$step.each(function(){
Comment = $(this).find(".Comment").val();
Grade = $(this).find(".Grade").val();
if(put your condition here)
else {
bOK = false;
return false
}
});
// Now test your condition with bOK
You should use the jQuery each() method to iterate over your $(".wizard-step2:visible") array of divs.
Have a look at this jsFiddle i've created to show how you can achieve this
EDIT :
This is the jist of the jsFiddle code here: -
$('.wizard-step2:visible').each(function(){
var txtBox = $(this).find('.comment');
var Select = $(this).find('.Grade');
var thisDiv = $(this).attr('id');
if(txtBox.val().length > 0 && Select.val().length > 0)
{
alert("values for " +thisDiv+ " are fine");
}
else
{
alert("please fill in both values for " + thisDiv);
}
});
I have a variable d that I use like this:
$(function() {
for(i = 1; i <= 31; i++) {
var d = '#days' + i;
if ($(d).attr("id").substr(4,2) == 11) {
$(d).addClass("date_has_event");
//console.log("diez");
} else {
console.log("otro");
}
}
}
However I get the following error in firebug:
$(d).attr("id") is undefined
index.html (L23) (?)()()
jquery.min.js (L27) onreadystatechange()()
jquery.min.js (L27) onreadystatechange()()
jquery.min.js (L21) nodeName()([function(), function()], function(), undefined)
onreadystatechange()()
I really don't understand why. Does anyone know?
Edit
I'm sorry for the poor explanation I had to run, here's what's going on a little bit more detailed. I am generating a calendar using javascript. each td has a different id (hence the #days + i) and I am running it from 1 to 31 so I can cover the longer months. However I am getting the error I mentioned above. I am also using the jQuery library to enable me to select more easily (i.e. instead of getElementById just #days)
Why not just check if i == 11, then do your processing on it? It would still only fire on $('#days11'). Edit: If you need to make sure the element exists as well, just slap that into the conditional.
$(function(){
for(i = 1; i <= 31; i++){
var d = '#days' + i;
// if($(d) && i == 11){
if(i == 11){
$(d).addClass("date_has_event");
//console.log("diez");
}else{
console.log("otro");
}
}
}
Ok, new answer. the way you are doing this is not very "jqueryish". lets step back a bit. from what I can tell you have an html structure something like:
<div id="days1"></div>
<div id="days2"></div>
...
You are then running this against every item with a days(num) id? A better solution is this, if you want to add a class to every element with a date in it, first apply a class:
<div class="days"></div>
<div class="days"></div>
Your code can then be
$(function(){
$(".days").each(function(i){
if($(this).substr(4,2) == 11){
$(this).addClass("date_has_event");
}
});
});
Since you are selecting by id, this is redundant:
if ($(d).attr("id").substr(4,2) == 11)
because the ID attribute of d is d.
Is most simple to do:
if (i == 11)
Missing the closing bracket?
$(function() {
for(i = 1; i <= 31; i++) {
var d = '#days' + i;
if (i == 11) {
$(d).addClass("date_has_event");
//console.log("diez");
} else {
console.log("otro");
}
}
// shouldn't the next line be });
}