JavaScript - Newbie Event Calendar Problem
First of all, thanks for looking!
I'm doing this nonprofit site for a students club in my college, and it needs an event calendar. I just have a bit of touch on javascript, and the only way this is going to be done in is javascript so I'm stuck with it. I took one of my assignments and modded it to the requirements of them. 1. A 6 month calendar. problem - I have to get thismonth, check whether its <July,then display Jan to June. Else July to December.(A semester calendar) figured it out. 2.Want to highlight a specific date, and place a link in it, so when somebody click the date, say a textarea in a form, displays the event details. problem - Have no idea on how to do it. Any help on this is warmly welcome ! My calendar.htm file Code: <html> <head> <title>Calendar</title> <link href="calendar.css" rel="stylesheet" type="text/css" /> <script src="calendar.js" type="text/javascript"></script> </head> <body> <div id="main"> <script type="text/javascript"> yearly(); </script> </div> </body> </html> My css file Code: #yearly_table {border: 1px solid black; font-size: 8pt; width: 500px; font-family: Arial, Helvetica, sans-serif; background-color: white} #yearly_title {color: white; background-color: rgb(223,29,29); letter-spacing: 6; font-size: 12pt} .yearly_months {vertical-align: top; border: solid 1px black} .monthly_table {font-size: 8pt; width: 100%; background-color: white} .monthly_title {background-color: rgb(223,29,29); color: white; letter-spacing: 4} .monthly_weekdays {border-bottom: 1px solid black} .monthly_dates {text-align: right} #today {font-weight: bold; color: rgb(223,29,29); background-color:#999; border: 1px solid black; text-align: center} My .js file Code: tes the month name in the monthly table writeDayNames() Writes the weekday title rows in the calendar table daysInMonth(calendarDay) Returns the number of days in the month from calendarDay writeMonthDays(calendarDay, currentTime) Writes the daily rows in the monthly table, highlighting the date specified in the currentTime parameter. writeDay(weekDay, dayCount, calendarDay, currentTime) Write the opening and close table row tags and the table cell tag for an individual day in the calendar. */ function yearly(calDate) { if (calDate == null) calendarDay=new Date(); else calendarDay = new Date(calDate); var currentTime = calendarDay.getTime(); var thisYear = calendarDay.getFullYear(); document.write("<table id='yearly_table'>"); document.write("<tr><th id='yearly_title' colspan='4'>"+thisYear+"</th></tr>"); var semMonth=calendarDay.getMonth(); var monthNum; if (semMonth <6) { monthNum = -1 } else { monthNum = 5; } for (var i=1; i<=2; i++) { document.write("<tr>"); for (var j=1; j<=3; j++) { monthNum++; calendarDay.setDate(1); calendarDay.setMonth(monthNum); writeMonthCell(calendarDay, currentTime); } document.write("</tr>"); } document.write("</table>"); } function writeMonthCell(calendarDay, currentTime) { document.write("<td class='yearly_months'>"); writeMonth(calendarDay, currentTime); document.write("</td>"); } function writeMonth(calendarDay, currentTime) { document.write("<table class='monthly_table'>"); writeMonthTitle(calendarDay); writeDayNames() writeMonthDays(calendarDay, currentTime); document.write("</table>"); } function writeMonthTitle(calendarDay) { var monthName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); var thisMonth=calendarDay.getMonth(); document.write("<tr>"); document.write("<th class='monthly_title' colspan='7'>"); document.write(monthName[thisMonth]); document.write("</th>"); document.write("</tr>"); } function writeDayNames() { var dayName = new Array("S", "M", "T", "W", "R", "F", "S"); document.write("<tr>"); for (var i=0;i<dayName.length;i++) { document.write("<th class='monthly_weekdays'>"+dayName[i]+"</th>"); } document.write("</tr>"); } function daysInMonth(calendarDay) { var thisYear = calendarDay.getFullYear(); var thisMonth = calendarDay.getMonth(); var dayCount = new Array(31,28,31,30,31,30,31,31,30,31,30,31); if ((thisYear % 4 == 0)&&((thisYear % 100 !=0) || (thisYear % 400 == 0))) { dayCount[1] = 29; } return dayCount[thisMonth]; } function writeMonthDays(calendarDay, currentTime) { var weekDay = calendarDay.getDay(); document.write("<tr>"); for (var i=0; i < weekDay; i++) { document.write("<td></td>"); } var totalDays = daysInMonth(calendarDay); for (var dayCount=1; dayCount<=totalDays; dayCount++) { calendarDay.setDate(dayCount); weekDay = calendarDay.getDay(); writeDay(weekDay, dayCount, calendarDay, currentTime); } document.write("</tr>"); } function writeDay(weekDay, dayCount, calendarDay, currentTime) { if (weekDay == 0) document.write("<tr>"); if (calendarDay.getTime() == currentTime) { document.write("<td class='monthly_dates' id='today'>"+dayCount+"</td>"); } else { document.write("<td class='monthly_dates'>"+dayCount+"</td>"); } if (weekDay == 6) document.write("</tr>"); } Similar TutorialsI am looking to add a calendar to my website in order to list events for each day on the calendar you click on. For example, the link below shows a calendar on the left, that when you click on a day it lists all the events that day. I have done a few searches, but am not sure if I can find a calendar that acts like this... Calendar Example Any help would be greatly appreciated! I need javascript event calendar sourcecode with highlighting of colors when dates selecting from datepicker of DHTMLgoodies calendar I am trying to trigger one custom function or another, depending on whether a radio button is checked or not. How can this be done? (I was hoping that "self" would be the ticket, but I think I was barking up the wrong tree.) Code: function toggleFieldsetByRadio(element){ if(SELF.checked){ enable(element); }else{ disable(element); } } How should I do this? I am hoping to use this function with an onchange event. ~ Mo I am using the following script to have a calander displayed in my form. It displays a calender on which a user can select a date. If the date is a friday, something else should happen in the form than when selecting other days (see final 15 lines, no need to be specific). The problem is that the code only works for months with 30 days in it. E.g. The september month works fine, when a friday is selected (javascript:setCalendarControlDate(2009,9,25)) the correct changes occur. For the October month (31 days) the same changes that occur correct in september occur in october when selecting thursday, but these should be when selecting friday instead! For November (30 days) everything works fine again, but then for December (31 days) the changes occur again at thursday instead of friday For February (2010) I need to select sunday to get the needed changes. Like I said, I think it has something to do with the amount of days in a month. Since the code works fine on months with 30 days, but not on months with other amounts of days. Can anyone tell me what's wrong in the code? Code: function positionInfo(object) { var p_elm = object; this.getElementLeft = getElementLeft; function getElementLeft() { var x = 0; var elm; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } while (elm != null) { x+= elm.offsetLeft; elm = elm.offsetParent; } return parseInt(x); } this.getElementWidth = getElementWidth; function getElementWidth() { var elm; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } return parseInt(elm.offsetWidth); } this.getElementRight = getElementRight; function getElementRight() { return getElementLeft(p_elm) + getElementWidth(p_elm); } this.getElementTop = getElementTop; function getElementTop() { var y = 0; var elm; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } while (elm != null) { y+= elm.offsetTop; elm = elm.offsetParent; } return parseInt(y); } this.getElementHeight = getElementHeight; function getElementHeight() { var elm; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } return parseInt(elm.offsetHeight); } this.getElementBottom = getElementBottom; function getElementBottom() { return getElementTop(p_elm) + getElementHeight(p_elm); } } function CalendarControl() { var calendarId = 'CalendarControl'; var currentYear = 0; var currentMonth = 0; var currentDay = 0; var selectedYear = 0; var selectedMonth = 0; var selectedDay = 0; var months = ['January','February','March','April','May','June','July','August','September','October','November','December']; var dateField = null; function getProperty(p_property) { var p_elm = calendarId; var elm = null; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } if (elm != null) { if(elm.style) { elm = elm.style; if(elm[p_property]) { return elm[p_property]; } else { return null; } } else { return null; } } } function setElementProperty(p_property, p_value, p_elmId) { var p_elm = p_elmId; var elm = null; if(typeof(p_elm) == "object") { elm = p_elm; } else { elm = document.getElementById(p_elm); } if((elm != null) && (elm.style != null)) { elm = elm.style; elm[ p_property ] = p_value; } } function setProperty(p_property, p_value) { setElementProperty(p_property, p_value, calendarId); } function getDaysInMonth(year, month) { return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1]; } function getDayOfWeek(year, month, day) { var date = new Date(year,month-1,day) var DayOfWeek = date.getDay(); if(DayOfWeek == 0) DayOfWeek = 6; else DayOfWeek--; return DayOfWeek; } this.setDate = setDate; function setDate(year, month, day) { if (dateField) { if (month < 10) { month = "0" + month; } if (day < 10) { day = "0" + day; } var dateString = day+"-"+month+"-"+year; dateField.value = dateString; hide(); } return; } this.changeMonth = changeMonth; function changeMonth(change) { currentMonth += change; currentDay = 0; if(currentMonth > 12) { currentMonth = 1; currentYear++; } else if(currentMonth < 1) { currentMonth = 12; currentYear--; } calendar = document.getElementById(calendarId); calendar.innerHTML = calendarDrawTable(); } function getCurrentYear() { var year = new Date().getYear(); if(year < 1900) year += 1900; return year; } function getCurrentMonth() { return new Date().getMonth() + 1; } function getCurrentDay() { return new Date().getDate(); } function calendarDrawTable() { var dayOfMonth = 1; var validDay = 0; var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth); var daysInMonth = getDaysInMonth(currentYear, currentMonth); var css_class = null; //CSS class for each day var table = "<table cellspacing='0' cellpadding='0' border='0'>"; table = table + "<tr class='header'>"; table = table + " <td colspan='2' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'><</a></td>"; table = table + " <td colspan='3' class='caltitle'>" + months[currentMonth-1] + "<br>" + currentYear + "</td>"; table = table + " <td colspan='2' class='next'> <a href='javascript:changeCalendarControlMonth(1);'>></a></td>"; table = table + "</tr>"; table = table + "<tr><th>Mon.</th><th>Tues.</th><th>Wed.</th><th>Thurs.</th><th>Fri.</th><th>Sat.</th><th>Sun.</th></tr>"; for(var week=0; week < 6; week++) { table = table + "<tr>"; for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) { if(week == 0 && startDayOfWeek == dayOfWeek) { validDay = 1; } else if (validDay == 1 && dayOfMonth > daysInMonth) { validDay = 0; } if(validDay) { if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) { css_class = 'current'; } else if (dayOfMonth == getCurrentDay() && currentYear == getCurrentYear() && currentMonth == getCurrentMonth()) { css_class = 'today'; } else if ((dayOfWeek == 5 || dayOfWeek == 6) && (dayOfMonth > getCurrentDay() || currentMonth > getCurrentMonth() || currentYear > getCurrentYear())) { css_class = 'weekend'; } else { css_class = 'weekday'; } if (((dayOfMonth < getCurrentDay() && currentMonth <= getCurrentMonth()) && currentYear <= getCurrentYear()) || currentYear < getCurrentYear()) { table = table + "<td><span class='dayinpast'>"+dayOfMonth+"</span></td>"; } else { table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>"; } dayOfMonth++; } else { table = table + "<td class='empty'> </td>"; } } table = table + "</tr>"; } table = table + "<tr class='header'><th colspan='7' style='padding: 3px; text-align:center;'><a href='javascript:hideCalendarControl();'>Close</a></td></tr>"; table = table + "</table>"; return table; } this.show = show; function show(field) { if (dateField == field) { hide(); return; } else { dateField = field; } if(dateField) { try { var dateString = new String(dateField.value); var dateParts = dateString.split("-"); selectedDay = parseInt(dateParts[0],10); selectedMonth = parseInt(dateParts[1],10); selectedYear = parseInt(dateParts[2],10); } catch(e) {} } if (!(selectedYear && selectedMonth && selectedDay)) { selectedMonth = getCurrentMonth(); selectedDay = getCurrentDay(); selectedYear = getCurrentYear(); } currentMonth = selectedMonth; currentDay = selectedDay; currentYear = selectedYear; if(document.getElementById) { calendar = document.getElementById(calendarId); calendar.innerHTML = calendarDrawTable(currentYear, currentMonth); setElementProperty('display', 'block', 'CalendarControlIFrame'); setProperty('display', 'block'); var fieldPos = new positionInfo(dateField); var calendarPos = new positionInfo(calendarId); var x = fieldPos.getElementLeft() - document.getElementById('table_left').scrollLeft; var y = fieldPos.getElementBottom() - document.getElementById('table_left').scrollTop; var w = calendarPos.getElementWidth(); var h = calendarPos.getElementHeight(); var ch = document.getElementById('table_left').style.height; ch = parseInt(ch.substring(0, ch.length-2)) + 143; var cw = document.getElementById('table_left').style.width; cw = parseInt(cw.substring(0, cw.length-2)) + 150; if(y+h > ch) y = ch - h; if(x+w > cw) x = cw - w; setProperty('left', x + "px"); setProperty('top', y + "px"); setElementProperty('left', x + "px", 'CalendarControlIFrame'); setElementProperty('top', y + "px", 'CalendarControlIFrame'); setElementProperty('width', w + "px", 'CalendarControlIFrame'); setElementProperty('height', h + "px", 'CalendarControlIFrame'); } } this.hide = hide; function hide() { if(dateField) { setProperty('display', 'none'); setElementProperty('display', 'none', 'CalendarControlIFrame'); dateField = null; } getSelectedDate('cd_pickup_date') } } var calendarControl = new CalendarControl(); function showCalendarControl(textField) { calendarControl.show(textField); } function hideCalendarControl() { calendarControl.hide(); } function setCalendarControlDate(year, month, day) { calendarControl.setDate(year, month, day); } function changeCalendarControlMonth(change) { calendarControl.changeMonth(change); } document.write("<div id='CalendarControl'></div>"); function getSelectedDate(value) { var selectedDate = document.getElementById('cd_pickup_date').value; var selectedDateArray = selectedDate.split("-"); var convertedDate = new Date(selectedDateArray[2],selectedDateArray[1],selectedDateArray[0]); var selectedDay = convertedDate.getDay(); var weekDay = new Array("Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"); if(weekDay[selectedDay] == "Friday") { document.collectionform.cd_saturday[0].checked = true; document.collectionform.cd_saturday[0].disabled = false; document.collectionform.cd_saturday[1].disabled = true; getAlternateAddress('Yes'); } else { document.collectionform.cd_saturday[1].checked = true; document.collectionform.cd_saturday[1].disabled = false; document.collectionform.cd_saturday[0].disabled = true; getAlternateAddress('No'); } } Hi, I have the script below working fine in IE but not FF, can any one help me?? The script creates new fields with calendar in a form, if new information is added to a field and then a new field is created the information is lost in FF Live demo: http://hotelendenia.com/sandbox/ Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Calendar Text Input</title> <script language="javascript" type="text/javascript" src="datetimepicker.js"></script> <script type="text/javascript"> function extend(m, e){ var e = e || this; for (var x in m) e[x] = m[x]; return e; }; function create(type, opt, parent){ var el = document.createElement(type); if (opt.style){ extend(opt.style,el.style); } delete opt.style; extend(opt,el); if (parent){ parent.appendChild(el); } return el; } fields = 0; function add_input(){ document.getElementById('input_container').innerHTML += ""+ fields +"<input id=\"cal"+ fields +"\" type=\"text\" size=\"25\"><a href=\"javascript:NewCal('cal"+ fields +"','ddmmyyyy')\"><img src=\"cal.gif\" width=\"16\" height=\"16\" border=\"0\" alt=\"Pick a date\"></a> <input type=\"text\" name=\"\" value=\"\"><br>"; fields += 1; } </script> </head> <body> <div> <form> <div id="input_container"> </div> <br /><input type="submit" value="submit"> </form> <a href="#" onclick="add_input()">add input</a> </div> </body> </html> Hello everyone, If I type the name, and I check and Gender Scholar, my button will appear What I am looking to: Check my buttons, and when I start typing the name, the button Submit appear, st if I delete the text, the Submit button disappear Here's the script: Code: <head> <script type="text/javascript" src="jquery.validate.js"></script> <script> $(document).ready(function(){ $("#commentForm").validate(); }); function check_required(){ //alert(document.getElementById('rdo_boursier_oui').checked); //alert(document.getElementById('txt_lastname').value != ""); if((document.getElementById('rdo_boursier_oui').checked == true || document.getElementById('rdo_boursier_non').checked == true) && (document.getElementById('rdo_sexe_eleve_m').checked == true || document.getElementById('rdo_sexe_eleve_f').checked == true) && (document.getElementById('txt_lastname').value != "" ) ) { document.getElementById ('submit_etape2').style.display='block'; }else{ document.getElementById ('submit_etape2').style.display='none'; } } </script> </head> <form action="#" method="post" id="commentForm"> <input class="submit" type="submit" name="submit_etape2" id="submit_etape2" value="" style="display:none;"/> <p class="p_float"> <label for="lastname">Votre nom<span class="required_red">*</span></label> <input type="text" name="txt_lastname" id="txt_lastname" value="" class="required" minlength="3" onchange="check_required();" /> </p> <p class="p_float rdo"> <label for="boursier">Boursier<span class="required_red">*</span></label> <input type="radio" name="rdo_boursier" id="rdo_boursier_oui" value="" class="rdo_sexe_eleve snd_inscription required" onclick="check_required();"/>Oui <input type="radio" name="rdo_boursier" id="rdo_boursier_non" value="" class="rdo_sexe_eleve snd_inscription required" onclick="check_required();"/>Non </p> <p class="p_float rdo"> <label for="sexe">Sexe<span class="required_red">*</span></label> <input type="radio" name="rdo_sexe_eleve" id="rdo_sexe_eleve_m" class="rdo_sexe_eleve snd_inscription required" onclick="check_required();" value="">M <input type="radio" name="rdo_sexe_eleve" id="rdo_sexe_eleve_f" class="rdo_sexe_eleve snd_inscription required" onclick="check_required();" value="">F </p> </form> Hi All, Need a bit of help here, need this SELECT to submit the page and end up at the below URL, correctly passing the GET values through the string. <code> <select name="dir-fact-misma" id="dir-fact-misma" class="text100" tabindex="" onChange="alta_nueva.action='alta.php?page=p2#alta'; return true;"> <option value="Si" <?php if(!isset($_POST['dir-fact-misma']) || $_POST['dir-fact-misma'] == 'Si') print "Selected='Selected '"; ?>>Si</option> <option value="No" <?php if(isset($_POST['dir-fact-misma']) && $_POST['dir-fact-misma'] == 'No') print "Selected='Selected '"; ?>>No</option> </select> </code> the form in which this SELECT is placed needs to be submitted so that other fields in the form are not lost, they are saved in Session Variables. the same javascript but activated through an onclick event works perfect elsewhere in the same form with the following code, i think its the onChange that doesn't work for some reason. <code> <input name="p1" type='submit' id="p1" onclick="alta_nueva.action='alta.php?page=p1#alta'; return true;" value='1' /> </code> the page is programmed in PHP. Any help is appreciated. Hello all, I'm wondering if anyone can offer advice on a simple (or so I thought!) Javascript menu I'm trying to create. I'm creating 5 buttons, using event handlers (onmouseover etc) which exchange 1 image for another. I did the first one fine - it worked perfectly, but as soon as I added the rest they all stopped working properly. The best I have got, is that the last link will do what it's supposed to regardless of which link I hover over! Which is strange. So the browser seems to be actioning the last thing on the list if that makes sense. It seems to me that I need to add an "if" type attribute, so "if" I hover over the home button, the home images change, as opposed to the last one on the list. This is the code I have so far for a single link - the rest are copies of this with adjustments made to the imgname and image sources obviously..... <div style="width:80px; height:20px;margin-top:20px;margin-left:85px;"><a href="about.html" onMouseOver="return changeImage()" onMouseOut= "return changeImageBack()" onMouseDown="return handleMDown()" onMouseUp="return handleMUp()" ><img name="aboutbutton" src="img/aboutn.png" width="80" height="20" border="0" alt="javascript button 1"></a> <script language="JavaScript"> upImage = new Image(); upImage.src = "img/abouth.png"; downImage = new Image(); downImage.src = "img/aboutc.png" normalImage = new Image(); normalImage.src = "img/aboutn.png"; function changeImage() { document.images["aboutbutton"].src= upImage.src; return true; } function changeImageBack() { document.images["aboutbutton"].src = normalImage.src; return true; } function handleMDown() { document.images["aboutbutton"].src = downImage.src; return true; } function handleMUp() { changeImage(); return true; } </script></div> Any suggestions on where I am going wrong would be wonderful. Thanks so much in advance! All the best Hello, I have a script I am using which works great, except when I copy the code and have multiple events it only shows the first one. This I believe is because it's calling the first class name of it's kind. I want the class's to be named the same thing (css styling) and because the site is going to be dynamically driven, but is there a way to modify my script so that instead of looking for the first class it recognizes the right class associated with the button clicked. If anyone can help me fix this problem I am having I would be most appreciative.. Code: <script language="javascript"> function toggle() { var ele = document.getElementById("commpopup"); if(ele.style.display == "block") { ele.style.display = "none"; } else { ele.style.display = "block"; } } </script> <div class="togglecomment"> <div class="popup" id="commpopup"> <div class="commentbtn"><a href="#"><img src="images/commenticon.png" align="absmiddle" />Comment</a></div> </div> <div class="button"><a href="javascript:toggle();"><img src="images/comment_btn.jpg" /></a></div> </div> Hey, im having another problem with my JavaScript. I wanted to call 2 functions inline, but I can't seem to do it. So I have added the function (add_event_listeners) to the function (load_doc) that is usually called. JavaScript debugger is saying: Code: Uncaught TypeError: Cannot read property 'addEventListener' of null JavaScript: PHP Code: //Get httpobject function getHTTPObject() { var http = false; if (window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http = new ActiveXObject("Microsoft.XMLHTTP"); } return http; } //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; function load_doc(doc, parent) { add_event_listeners(); document.getElementById(parent).innerHTML = "Fetching data..."; var http = getHTTPObject(); if (http != undefined) { http.onreadystatechange = function() { req_doc(doc, parent, http); }; http.open("GET", doc, true); http.send(""); } } function req_doc(doc, parent, req) { if (req.readyState == 4) {//only if req is loaded if (req.status == 200) {//And if its okay document.getElementById(parent).innerHTML = req.responseText; } else { document.getElementById(parent).innerHTML = "Error fetching data: " + req.status + "\n" + req.statusText; } } } //Script used to hide elements. Usage: expand(element id) function expand(elm) { var ex = document.getElementById(elm).style.display; if (ex == "none") { var obj = document.getElementById(elm); obj.style.display = "inline"; } else if (ex == "inline") { var obj = document.getElementById(elm); obj.style.display = "none"; } } function add_event_listeners() { addEvent(document.getElementById('username'), "click", check_database); addEvent(document.getElementById('email'), "click", check_database); addEvent(document.getElementById('password_2'), "blur", check_password); } var check_database = function() { check_database_existing(this); }; var check_password = function() { compare_fields(this); }; function check_database_existing(obj) { } function compare_fields(obj) { var field2 = obj.id.split("_"); field2 = document.getElementById(field2[0]).value; if (obj.value == field2) { if (obj.value.length >= 4) { document.getElementById("pass_status").style.color = "#00CC00"; document.getElementById("pass_status").innerHTML = "OK!"; } else { document.getElementById("pass_status").innerHTML = "Please must be between 5 - 14 characters long! "; document.getElementById("pass_status").style.color = "#FF0000"; } } else { document.getElementById("pass_status").innerHTML = "Passwords do not match!"; document.getElementById("pass_status").style.color = "#FF0000"; } } HTML: Code: <div style="border-color:#090; border-width:1px; border-style:solid;"> <div class="login_button register_button" onClick="load_doc('pages/forms/login_form.php', 'login_form')">Back to login</div> <h1>Register</h1> <h3>DrawSomething - WordGuesser</h3> <br /> <form id="register" action="php/register.php" method="post"> Username<br /><h4 id="username_status">(waiting)</h4><br /><input type="text" name="username" id="username" class="text login_field"><br /> Email<br /><h4 id="email_status">(waiting)</h4><br /><input type="email" name="email" id="email" class="text login_field"><br /> --<br /> Password<br /><input type="password" name="password" id="password" class="text login_field"><br /> Retype<br /><h4 id="pass_status">(waiting)</h4><br /><input type="r_password" id="password2" name="password" class="text login_field"> <br /> <input type="submit" value="Register" class="button green" /> </form> </div> I'm trying to simulate a textfield on a canvas; that is when clicking on the text box a cursor appears and blink. My problem here is when I create more than one object, the event listener will work only on the last object created. Here is my code: Javascript Code: var canvas; var ctx; var MousePosX; var MousePosY; var Cursor_Width = 1; var Cursor_Height = 21; var Height = 27; var LapseTime = 800; function init(CanvasName) { canvas = document.getElementById(CanvasName); ctx = canvas.getContext("2d"); } /* Create Textfiled */ function Textfield(x, y, w) { Textfield.prototype.x = x; Textfield.prototype.y = y; Textfield.prototype.w = w; Textfield.prototype.Cursor_PosX = x + 3; Textfield.prototype.Cursor_PosY = y + 3; // draw rectangle ctx.beginPath(); ctx.rect(this.x, this.y, this.w, Height); ctx.closePath(); ctx.stroke(); // listen for mouse click event canvas.addEventListener("mousedown", function(evt) { // calculate mouse coordination on canvas MousePosX = evt.clientX - canvas.offsetLeft; MousePosY = evt.clientY - canvas.offsetTop; // if mouse coordination is within texfield display cursor if((MousePosX > Textfield.prototype.x && MousePosX < (Textfield.prototype.x + Textfield.prototype.w)) && (MousePosY > Textfield.prototype.y && MousePosY < (Textfield.prototype.y + Height))) { Textfield.prototype.cursor(); } }); } /* Cursor for textfield */ Textfield.prototype.cursor = function() { // alert("good"); ctx.beginPath(); ctx.strokeStyle = "black"; ctx.rect(this.Cursor_PosX, this.Cursor_PosY, Cursor_Width, Cursor_Height); ctx.closePath(); ctx.stroke(); setTimeout("Textfield.prototype.animate_cursor()", LapseTime); }; /* Change color of cursor to white to make blinking effect */ Textfield.prototype.animate_cursor = function() { ctx.strokeStyle = "white"; ctx.stroke(); setTimeout("Textfield.prototype.cursor()", LapseTime); }; HTML Code: <!DOCTYPE HTML> <html> <head> <style> #MyCanvas { border: 1px solid #000000; } </style> <script src="widgets1.js"></script> <script> window.onload = function () { init('MyCanvas'); var tf1 = new Textfield(10.5, 10.5, 150); var tf2 = new Textfield(10.5, 50.5, 150); }; </script> </head> <body> <br /><br /><br /> <center> <canvas id="MyCanvas" width="700" height="500"> </canvas> </center> </body> </html> What i want to achieve here is have my event listener on any textfield created on the canvas. i m very new to this thread so i will try to be as clear as possible i m try to create a website where i n have inserted a menu (this menu template i found online which is free.) Code: <div id="menu"> <ul class="menu"> <li><a href="#" class="parent"><span>Home</span></a> <li><a href="#"><span>Cities</span></a> <div><ul> <li><a href="#"><span>Pune</span></a></li> <li><a href="#"><span>Mumbai</span></a></li> <li><a href="#"><span>Delhi</span></a></li> <li><a href="#"><span>Madras</span></a></li> </ul></div> </li> <li><a href="#"><span>Login</span></a></li> <li><a href="#"><span>About Us</span></a></li> <li class="last"><a href="#"><span>Contact Us</span></a></li> </ul> </div> what i am trying to do here is when i click on city (one of the menu) it should read the values from database table (the table name is cityCode. this table contains two rows first cityName and second cityCode) n depending on which city is selected it should retrieve the code of that city. also where to save that retried value because i want to use that retried code to extract value from another table. Quick question, I found this code snip on stackoverflow and it has one little bug. When you touch / move in the element, the console.log is being fired. If you continue to drag / move outside the element, the console.logs still continue to fire. So it seems that once the event is started it's no longer confined to the element its being assigned to. Any ideas on how to keep it bound to the element? Here is the code: Code: $('#someElm').bind('touchmove',function(e){ e.preventDefault(); var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; console.log(touch.pageY+' '+touch.pageX); }); Thanks in advanced. Realizing that form input placeholders aren't universally recognized among browsers, I began changing all of mine using onblur and onfocus handlers instead. As an example, I used the following code, which works in most cases: Code: <input type="text" name="example" maxlength="5" value="Example" onblur="if(this.value=='') this.value='Example';" onfocus="if(this.value=='Example') this.value='';"/> At first, I coded all of the inputs without a value attribute. But, when the page initially loaded, the fields would load empty, and the value/placeholder wouldn't appear until the field had been "focused" and then "blurred" again. Adding the value attribute seemed to correct that problem, again, for the most part. I have some text fields that appear only after I select a particular radio button or select option. Problem is, when the radio is clicked, the field appears, but even with the value attribute in place, the field appears void. I'm not sure what is different, or what I'm doing wrong. Here's the javascript code with the radio button (note:everything works except that the "placeholder" doesn't show when the field first appears): Code: function showfield() { document.forms[0].otherRelation.value = ""; document.getElementById("newBox").style.display = "none"; var r = document.forms[0].relation; var len = r.length; for (var i =0; i<len; i++) { if (r[i].checked && r[i].value == "Otherrelation" ) { document.getElementById("newBox").style.display = "inline"; } } } <input type="radio" name="relation" value="Otherrelation" onclick="showfield()"/>Other <span id = "newBox" style="display:none">: <input type = "text" name="otherRelation" size="35" value="Your Relationship" onblur="if(this.value=='') this.value='Your Relationship';" onfocus="if(this.value=='Your Relationship') this.value='';"/> </span> Thanks for any help. Sorry so long. Here is a javascript/html code that changes a text phrase to something else on mouseover but it doesn't return to its original state before the event happened. The code is below. Thank you for your help. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script></script> <title>Javascript</title> <style type="text/css"> div { font-family: Georgia } </style> </head> <body> <script type="text/javascript"> function changetext() { var textchange2 = "~Home~" ; var id = document.getElementById("A"); id.innerHTML=textchange2; } </script> <div id="A" onmouseover="changetext();">Home</div> </body> </html> Hi forum, I am trying to attach an event to a dynamically produced button, and then use stopPropagation and preventDefault. Code: function chapter12_nodeOne() { //create an element var element = document.createElement('input'); //set some attributes element.setAttribute('type', 'button'); element.setAttribute('value', 'submit'); element.setAttribute('id', 'myBtn'); //appendd the element into a DIV document.getElementById('myDiv').appendChild(element); //uses EventUtil to attach an event listener EventUtil.addHandler(element, 'click', function() { alert('event attached'); }); var flag = confirm('prevent default behavior of button?'); if (flag) { var el = document.getElementById('myBtn');/////////////////////////(1) var ev = el.onclick; } } var EventUtil = { addHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.addEventListener) { element.addEventListener(type, handler, false); } //if user is browsing with IE else if (element.attachEvent) { element.attachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.removeEventListener) { element.removeEventListener(type, handler, false); } //if user is browsing with IE else if (element.detachEvent) { element.detachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = null; } } }; But when debugging I see under el on the line marked with (1) that the onclick event is null. What am I doing wrong?! PS:the event is attached, when I click on the button I get an alert message Hello, I'm a newbie to javacript and indeed programming. The code below is obviously very simple but i can't figure out where i'm going wrong. Could anybody help? [CODE] function getRandomNumber(aNumber) /* ***************************************************************************** /* { var randomNumber; randomNumber = Math.random() * (aNumber); return Math.floor(randomNumber); } /*******************************************************************************/ function randomString(aString, aDelimiter) { var termArray = new Array(); termArray = aString.split(aDelimiter); var randomNumber = getRandomNumber(termArray.length) ; var randomTerm; for(var i = 0; i < termArray.length; i++) { if (termArray[i] != randomNumber) { termArray[i] = termArray[i+ 1] ; } else { termArray[i] = randomTerm; } } return randomTerm; } document.write(''+randomString('how$are$you','$'); [CODE] **just realised I have put this in the wrong section
Hi I am populating the textboxes using a button . The code is Code: <input type="button" name="bt_autoFill" id="id_autoFill" value="Auto Fill" onclick="fillComponents()"/> this calls the javascript function Code: <script type="text/javascript"> function fillComponents() { document.getElementById("id_name").setAttribute("value","zedan"); document.getElementById("id_country").setAttribute("value","USA"); document.getElementById("id_Address").setAttribute("value","South Boulev."); } </script> Now the code works fine when i click it the first time. However if i change a value or erase something in the textboxes the function dosnt work. all the elements are text boxes. Could you tell me what I am doing wrong ?? why doesnt it work the second time?? is it possible to capture the control.event or element.event that was fired to invoke the onbeforeunload event. for example, if a button is clicked and it causes the onbeforeunload event to fire can i determine which button was clicked. thanks |