Do I need to load JQuery to make this work? - javascript

I have two drop down boxes that represent year intervals. The user will select a year from the first one (say 2002), and the next drop down box will automatically be filled with years that equal or are greater than the first (2002 and above). I believe I have the correct javascript code (year.js).
Here it is:
$("#first").change(function(){
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i=val; i<=n;i++){
$("#second").append("<option>" + i + "</option>");
}
});
Here is part of my html form code:
<body>
<script src="year.js"></script>
<select id= "first">
// Here, I gather my years from my database
</select>
<select id= "second">
</select>
When I run this, Nothing happens with my second drop down menu. Do I need to load something else into my code like JQuery? If so, how do I do that? Sorry, I am not very familiar with JQuery. Any help would be greatly appreciated.

Yeah you need to load jQuery library to use jQuery function.
you must load the jQuery library before using it's function.
example
<script src="jquery.js"></script> //a local version
or
<script src="http://code.jquery.com/jquery-latest.min.js.js"></script>
<script src="year.js"></script>
Download jQuery library from http://jquery.com/download/
Updated after OP's comment about http://jsfiddle.net/YNuna/1/
you have laoded jQuery library in fiddle.I have marked it with red color in the image below.
also wrap you code in $(document).ready(function ()
$(document).ready(function () {
$("#first").change(function () {
var val = $("#first option:selected").html();
$("#second").html("");
var d = new Date();
var n = d.getFullYear();
for (i = val; i <= n; i++) {
$("#second").append("<option>" + i + "</option>");
}
});
});

If you're copy-pasting javascript code from anywhere and you see a $ sign, a good rule of thumb is that it uses jQuery.
See here for adding it to your page: http://learn.jquery.com/about-jquery/how-jquery-works/

Related

JavaScript/Jquery not executing my functions

I am trying to create a basic image rotate. I have my images stored locally by name in a folder called comics. each comic name is comic_(plus the number). It wont do anything when I click my buttons. It wont even disable my previous button. Please help. Thank you guys.
Here is my JS/Jquery...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//declare my variables
var comic_img = $('#comicpane').find('img')
var current_comic_number = parseInt(comic_img.attr('class').replace('comic_',''))
var prev_comic = current_comic_number - 1;
var next_comic = current_comic_number + 1;
});
if (current_comic_number == 1){
//disable the prev button
$("#prev").attr('disabled','disabled');
//When the user clicks on a nav item
$(".nav_link").on('click')function(){
//Get the button they clicked
current_button = $(This);
if (current_button.attr('id')) == 'next'
{
comic_img.attr('class','comic_') + next_comic + ".jpg";
comic_img.attr('src','comics/comic_1') + next_comic;
//change variables to reflect current comic
current_comic_number +=1;
next_comic +=1;
prev_comic +=1;
}
//Only other option
else
{
comic_img.attr('src','comics/comic_1') + prev_comic + '.jpg';
comic_img.attr('class','comic_') + prev_comic;
//Change variables to reflect comic
current_comic_number -=1;
next_comic -=1;
prev_comic -=1;
}
//If comic number is less or equal to 1 and prev button is Not disabled, it needs to be disabled.
if (current_comic_number <=1 && !$('#pev').attr('disabled','disabled'))
{
$('#prev').removeAttr('disabled')
}
}
}
</script>
Here is my HTML...
<html>
<head>
<title>SRS Comic Zone</title>
<link rel="stylesheet" href="srscomiczone.css" media="screen">
</head>
<body>
<div id="header">
<img id="header" src="HeaderPicture.png" align=center>
</div>
<div class="comiczone" id="comicpane" align=center>
<img class="comic_1" src="comics/comic_1.jpg">
</div>
<div id="comicNav" align=center>
<button id="prev" class="nav_link">Previous</button>
<button id="next" class="nav_link" >Next</button>
</div>
</body>
</html>
few mistakes,
1) this is how you call a click event
$(".nav_link").on('click',function(){
....
and not
$(".nav_link").on('click')function(){ //replace this with above code
you might also need to delegate your selector if it is added dynamically.....
2)
current_button = $(This);
should be
current_button = $(this);
3) also, notice..if you are using jquery 1.6+, use prop() instead of attr()
$("#prev").prop('disabled',true);
instead of
$("#prev").attr('disabled','disabled');
4) add all your codes inside document.ready $(document).ready(function(){ //here }); function and not outside.
5) most important, you either have to include the script (js file) inside you html page. or paste all your script codes inside <head> tag of your HTML file
Also this stuff should be wrapped by:
$(document).ready(function() {
$(".nav_link").on('click',function(){
...
});
not just your var declarations.
Your code is trashy. Better use tool like JS Hint (or other JS validator, or even Chrome/Firefox with web console) to actually make sure code can even run.
Here are (some) of the issues with it:
you're missing semicolons
your .ready() function is (as I believe) ending prematurely
you're doing click handling wrong (pointed out by #bipen)
your if statements are messed up
you (probably) haven't included scripts into the HTML document
Ad 1
Missing semicolon here:
var comic_img = $('#comicpane').find('img')
Ad 2
current_comic_number is a local variable in $.ready(), but it's used outside of this function
Ad 3
It's not valid JS (see #bipen's answer):
$(".nav_link").on('click')function(){
Ad 4
It's not valid if statement:
if (current_button.attr('id')) == 'next'
it should be:
if (current_button.attr('id') === 'next')
Ad 5
Use <script> tag only inside *.html file, not in *.js. On example:
<script src="main.js"></script>
Then, put all of your JS code into main.js file.

Javascript Calculation function - Not calculating in html

I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100
PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.
This is to get the percentage value of the discount against the list and the RRP.
Please review the code before HTML:
<script type="text/javascript">
discountFinal(#OriginalPrice, #ListPrice);
</script>
<div id="discountCode">
<span id="spanish"></span>
<span id="spanishtwo">%</span>
</div>
Javascript:
var discountFinal = function (firstly, secondly) {
var totalfirst = secondly - firstly;
var totalsecond = totalfirst / secondly;
var totalthird = totalsecond * 100;
if (document.getElementById("discountCode").innerHTML === null) {
document.getElementById("spanishtwo").innerHTML.replace("%", "")
} else {
document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
}
};
I dont think i am calling the function within the html properly. Can someone assist with this please.
http://jsfiddle.net/xwzhY/
I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:
http://jsfiddle.net/bmonty/xwzhY/4/
Edit after comment from OP.
You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.
This will work:
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
But this will throw an error:
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.
It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/
Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:
function discountFinal(firstly, secondly){
...
Trying put "" around your perl variable, you need to pass the value

Javascript Page Load Total

I've created a form that is used to calculate monthly expenses. The problem I'm having is on the last page I'm gathering information from previous pages (session to data) that auto fills the fields on the last page. I've created a Javascript that is suppose to subtract the five fields on the page for a grand total but this doesn't work. If I delete the session to data from the load section the Javascript works perfectly.
Page in Question:
http://www.garranteedsolutions.com/budget?chronoform=BudgetPage7
Javascript:
window.addEvent('domready', function() {
$('spendable').addEvent('change', rekenen1);
$('housetotal').addEvent('change', rekenen1);
$('cartotal').addEvent('change', rekenen1);
$('creditortotal').addEvent('change', rekenen1);
$('misctotal').addEvent('change', rekenen1);
});
function rekenen1(){
$('grandtotal').value = Number($('spendable').value) + Number($('housetotal').value) + Number($('cartotal').value) + Number($('creditortotal').value) + Number($('misctotal').value) ;
}
This is the code that I had been using but it requires a change in the form box to perform the action. I've tried this
Javascript:
window.addEvent('domready', function() {
rekenen1;
$('spendable').addEvent(rekenen1);
$('housetotal').addEvent(rekenen1);
$('cartotal').addEvent(rekenen1);
$('creditortotal').addEvent(rekenen1);
$('misctotal').addEvent(rekenen1);
});
function rekenen1(){
$('grandtotal').value =
Number($('spendable').value) + Number($('housetotal').value)
+ Number($('cartotal').value) + Number($('creditortotal').value)
+ Number($('misctotal').value);
}
This is a continuation of me searching for help starting here: http://www.chronoengine.com/forums/viewtopic.php?f=2&t=67427&p=269741#p269741
I don't know Javascript very well and I'm so close to having this form completed. I just can't get the Grand Total to tally up.
The problem is that the events are only firing when you change the values of the form. The form its readonly so they cannot be changed.
Anyway, here is the code optimized:
window.addEvent('domready', function() {
var rekenen1 = function(){
var grandTotal = 0;
$$('#spendable, #housetotal, #cartotal, #creditortotal, #misctotal').each(function(el){
if(el.value.length > 0) grandTotal += el.value.toFloat();
});
$('grandtotal').value = grandTotal;
};
$$('#spendable, #housetotal, #cartotal, #creditortotal, #misctotal').addEvent('onchange', refenen1);
});
That should work. The function checks if the fields have value on them and if they have, they are included in the calculation.
The second code you made fires the error because you are missing a parameter in the addEvent function.
I hope that this can help you :)
This seemed to work! So now I'm trying to figure out how to get commas for the thousands. So if I input 1200 it displays 1,200.
window.addEvent('domready', function() {
$('grandtotal').value = Number($('spendable').value) + Number($('housetotal').value) + Number($('cartotal').value) + Number($('creditortotal').value) + Number($('misctotal').value);
});
Thank you so much for your help!

Jquery or Javascript that display content based on the date HELP

Jquery or JavaScript that displays content based on specifics date period
so we have like 3 dates
12/3/2010
12/11/2010
12/20/2010
and
Div Contents
Content 1 should be displaying from 12/3 to 12/11
Content 2 should be display from 12/11 to 12/20
and Content 3 should be displaying from 12/20 there after
First, like others said this whole thing is bad idea as you're depending on the client machine date/time and correct approach would be doing that in server side.
Anyway, guess you have your reasons so here is jQuery solution.
Have such HTML:
<div class="DateDiv"><span class="DateRange">1/1/2010 to 1/1/2011</span>I'll be visible during 2010</div>
<div class="DateDiv"><span class="DateRange">1/1/2011 to 1/1/2012</span>I'll be visible during 2011</div>
<div class="DateDiv"><span class="DateRange">1/1/2012 to 1/1/2013</span>I'll be visible during 2012</div>
Put the date range inside a span inside each div with the class "DateRange".
Next, have such CSS to have them initially hidden:
<style type="text/css">
.DateRange, .DateDiv { display: none; }
</style>
And finally, this script: (jQuery)
<script type="text/JavaScript">
$(function() {
$(".DateDiv").each(function(index) {
var sRange = $(this).find(".DateRange").html();
var arrTemp = sRange.split(" to ");
var dtFrom = new Date(arrTemp[0]);
var dtTo = new Date(arrTemp[1]);
var dtNow = new Date();
if (dtNow >= dtFrom && dtNow <= dtTo)
$(this).show();
});
});
</script>
Test case is available here feel free to mess around with it: http://jsfiddle.net/2BHLd/
I've created a simple code. It should work as you want (if I have understood you well).
I know, there's no doctype in my HTML and there are some missing tags. The HTML I've provided is just a kind of template.
<html>
<head>
<script type="text/javascript">
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth();
var day=date.getDate(); // fixed
function SetDivContent() {
var div=document.getElementById('date_dependent');
if (year==2010 && month==11) { // fixed (the JavaScript months order is 0-11, not 1-12)
if (day>=3 && day<11) { // the following content will be displayed 12/03/2010, 12/04/2010, [...], 12/09/2010, 12/10/2010
div.innerHTML='content 1';
}
else if (day==11 || day==12) { // this one will be displayed 12/11/2010 and 12/12/2010
div.innerHTML='content 2';
}
else if (day>12) { // this one - 12/13/2010 and later, until the end of December
div.innerHTML='content 3';
}
}
else if (year==2011 && month>=0) div.innerHTML='content 3'; // OPTIONAL - just to ensure that content 3 is displayed even after December.
}
</script>
</head>
<body onload="SetDivContent()">
<div id="date_dependent"></div>
</body>
</html>
Please note that if you want to hide some data from users if the specified date hasn't come yet, you should better use something server-side for security reasons. Otherwise, any user may just read the page's source. Also remember that the following code is executed when the body is loaded, i.e. each time a user refreshes the page.
EDIT: Warning: there were two bad lines (I've made a mistake before). Anyway, I've fixed them. The current code works, I've tested it.

creating an object/class and using it in jquery

Hi sorry if the name of my question is not correct.
i am trying to create an image rotator, but i would like to be able to re-use it more than once in a page, so i am trying to create it as an object/class.
I have about 5 or 6 images on a page.
i would like to have each image as a rotator, displaying a new image every 2 seconds or so.
<img src="uploads/Range_Images/p6-7.jpg" class="myclass1"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass2"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass3"/>
<script type=text/javascript>
$Rotator1 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass1');
setInterval($Rotator1.rotateImage(), 1000);
$Rotator2 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass2');
setInterval($Rotator2.rotateImage(), 1000);
$Rotator3 = new imageRotator1('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass3');
setInterval($Rotator3.rotateImage(), 1000);
</script>
Thats the code i am using to display the images and to create an instance of my rotator class
I can think of a few issues i am not sure of the answers too despite googling for hours!
Firstly here is my code (i am mixing javascript with jquery which is probably where i am going wrong to start with...
<script type="text/javascript">
$(document).ready(function(){ // maybe this should not be used when creating a object/class???
// i want to use this function as a class if possible
function imageRotator($images_str, $class){
// set up the vars
this.myImg = $images_str; //string containing image names
this.myClass = $class; //string containing class of image to change
this.imagelist = this.myImg.split(':'); //split the image string into an array
this.index = 1; // set the current index count
// maybe this is where i am going wrong, as in jquery $(this) refers to the current selector and maybe this.myclass (from from the imageRotator object does not work??
// is it possible to reference a value from an object in jquery?
function prototype.rotateImage(){
$(this.myclass).fadeOut('fast', function(){
$(this).attr('src', this.imagelist[this.index]);
$(this).fadeIn('fast', function(){
if (this.index == this.imagelist.length-1){
this.index = 0;
}else{
this.index++;
};
});
});
};
};
});
</script>
I am by no means an expert in programming, but i am sure this should be possible somehow.
any help would be much appreciated :P
update:
ok have modified the code slightly as per castrohenges reply:
<script type="text/javascript">
$(document).ready(function(){
var imageRotator = function($images_str, $class){
// set up the vars
this.myImg = $images_str; //string containing image names
this.myClass = $class; //string containing class of image to change
this.imagelist = this.myImg.split(':'); //split the image string into an array
this.index = 1; // set the current index count
};
function imageRotator.prototype.rotateImage(){
$(this.myclass).fadeOut('fast', function(){
$(this).attr('src', this.imagelist[this.index]);
$(this).fadeIn('fast', function(){
if (this.index == this.imagelist.length-1){
this.index = 0;
}else{
this.index++;
};
});
});
};
});
</script>
</head>
<body>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass1"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass2"/>
<img src="uploads/Range_Images/p6-7.jpg" class="myclass3"/>
<script type=text/javascript>
$(document).ready(function(){
$Rotator1 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass1');
setInterval($Rotator1.rotateImage(), 1000);
$Rotator2 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass2');
setInterval($Rotator2.rotateImage(), 1000);
$Rotator3 = new imageRotator('p12-13.jpg:p18-19.jpg:p4-5.jpg:p8-9.jpg:p6-7.jpg:p10-11.jpg:p14-15.jpg:p16-17.jpg', '.myclass3');
setInterval($Rotator3.rotateImage(), 1000);
});
</script>
</body>
i was getting an error: image rotator not defined on line 45
hence changing it to
var imageRotator = function($images_str, $class){....};
but the error is still there?
will try recreating this script following the plug-in guidelines and see where i get....
If you want to use prototyping you need to change
function prototype.rotateImage(){
and place it outside of the imageRotator function. Like so:
function imageRotator($images_str, $class){ ... }
imageRotator.prototype.rotateImage = function() { ... }
Alternatively you could also take a look at this jQuery plugin http://malsup.com/jquery/cycle/ - this is the first one I found, but I'm sure there will be more out there.
If you do want to use your own custom code I recommend wrapping it up as a jQuery plugin - http://docs.jquery.com/Plugins/Authoring. That way you don't have to worry to much about class architecture and everything will be nicely encapsulated in the jQuery object.

Categories