JavaScript - I Have 2 Var & 2 Function Statements Which Are Almost Identical; One Partially Works
Hi there,
I've modified some code I found with a single variable & function to not allow certain keyboard input from a form (I eventually want this info to go into a cookie). I made two variables & functions; one which would not allow text, and one which would not allow numbers. The (new) text variable/function works fine, but the (modified) number variable/function only disallows the numbers 8 & 9. Please look at my code, try it (it doesn't work in IE8 or Firefox), and let me know how to fix it. Thanks, mitchellA PS: this is my first posting and I'm not sure I've followed the rules properly. Code: <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Character Removal Test - by mitchellA</title> <script language="javascript" type="text/javascript"> /* Visit http://www.yaldex.com/ for full source code and get more free JavaScript, CSS and DHTML scripts! */ /* This script has been heavily modified from the original by mitchellA. */ <!-- Begin var only_t = /[$\\@\\\#\%\^\&\*\(\)\[\]\+\ \{\}\`\~\=\|\/\?\.\,\<\>\'\"\!\:\;\0\1\2\3\4\5\6\7\8\9]/; var only_n = /[$\\@\\\#\%\^\&\*\(\)\[\]\+\ \{\}\`\~\=\|\/\?\.\,\<\>\'\"\!\:\;\a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z]/; function chk_t(val) { var strPass = val.value; var strLength = strPass.length; var lchar_1 = val.value.charAt((strLength) - 1); if(lchar_1.search(only_t) != -1) { var tst = val.value.substring(0, (strLength) - 1); val.value = tst; } } function chk_n(val) { var strPass = val.value; var strLength = strPass.length; var lchar_2 = val.value.charAt((strLength) - 1); if(lchar_2.search(only_n) != -1) { var tst = val.value.substring(0, (strLength) - 1); val.value = tst; } } function chk2(form) { if(form.value.length < 1) { alert("Missing something."); return false; } if((form.value.search(only_t) == -1) ||(form.value.search(only_n) == -1)) { alert("Seems to be working."); return false; } } // End --> </script> </head> <form name=get_info onSubmit="return chk2(this.f_name); return chk2(this.l_name); return chk2(this.exp_hrs);"> <br> <br> First Name: <input type="text" name="f_name" size="25" maxlength="15" value="" onKeyUp="javascript:chk_t(get_info.f_name);"> <br> <br> Last Name: <input type="text" name="l_name" size="25" maxlength="20" value="" onKeyUp="javascript:chk_t(get_info.l_name);"> <br> <br> How many minutes do you want your cookie to last (10 - 60): <input type="text" name="exp_mins" size="3" maxlength="2" value="" onKeyUp="javascript:chk_n(get_info.exp_mins);"> <br> <br> <input type=submit value=Continue> <br> </form> <body> </body> </html> Similar TutorialsHi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave My problem is that i have multiple math calculations within different functions that have multiple switch statements that get calculated with an onclick="functionOne()" for each radio button and before i can calculate the outcome for some reason i must fully insert a value for every input as well as check every raidio button before i get to the end of my list. I wish to simply allow the user to fill out as many fields as he wishes leaving some bank without being restricted to do every single one.. Thank you in advance
Hi, this is a bit of a long question, but I'm not sure what's relevant, so feel free to ignore the irrelevant bits. I have this function: Code: function searchLocations() { var found = false; var input = document.getElementById('autocomplete').value; var inp = input.toLowerCase(); var count = 0; map.closeInfoWindow(); for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); elabels[j].hide(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); var point = gmarkers[j].getPoint(); bounds.extend(point); elabels[j].show(); count++; var q=j; } } if (count==1) { map.setZoom(15); myclick(q); elabels[q].hide(); } else if (count>1) { centerZoom(); } else { alert("No matches found. Please check your spelling or refine your search."); } } which does the following: - checks for matches in the array vs the input from the text box - shows the matching markers on the map - takes note of where the markers are and increases the bounds area to be displayed (this is the var point = gmarkers[j].getPoint(); bounds.extend(point); bit - keeps count of how many matches were made - if it's one match, zooms the map to 15, shows an infowindow - if it's more than one match, fires centerZoom();, another function that either zooms the map in or out (depending on the bounds) so that the matched markers are displayed. Which is all great, as you can see if you type "par" into the search box top right here. The problem is when you type in the second partial match - say "bl" - then it doesn't just use the 3 points from the match, but all the points from the array, meaning that the map zooms out as if it were going to show every marker, even though it only shows a few. So my question (finally) is how can I make sure that the var point = gmarkers[j].getPoint(); bounds.extend(point); bit only picks up the markers that are currently matched? thanks in advance for any suggestions Hi I am not really sure where to start with this as my function works perfect in IE 6. However when I select one of my categories and hit submit in Firefox or IE7 or 8 nothing happens. No error message. Just nothing. How can I get this working for firefox and IE7/8? Code: <script language="JavaScript"> var categories=[]; var categorieslist=[]; var thecategories=[]; var ItemDetails=[]; var selDate=[]; var content=[]; var imagePaths=[]; var art=[]; var aTheDates=[]; var aTheYear=[]; var catDM=" "; var catUrl=""; var startposition=0; var theImage=""; var pageDectect=0; var thepage=0; var pc=0; var starty=0; var pagenumber=0; var filteredlist="<ul class='press-items'>"; function changeFilter(){ var selCategory=document.getElementById("browsetopic").value; //alert(selCategory + " aha"); var selYear=document.getElementById("browseyear").value.substring(2,4); var selMonth=document.getElementById("browsemonth").value; //var selDate=document.getElementById("browsemonth").value + "/" + document.getElementById("browseyear").value.substring(2,4); //alert(pagenumber); for(pagenumber;pagenumber<art.length;pagenumber++){ //alert(selDate + "=" + aTheDates[pagenumber]); //alert(selYear + "=" + aTheYear[pagenumber]); //alert(selCategory + "=" + categories[pagenumber]); if(((selCategory=="nofilter"||categories[pagenumber]==selCategory))&&(selYear==aTheYear[pagenumber]||selYear=="00")&&(selMonth==aTheDates[pagenumber]||selMonth=="00")){ filteredlist=filteredlist+art[pagenumber]; } } filteredlist=filteredlist+"</ul>"; //alert(filteredlist); document.getElementById("theid").innerHTML=filteredlist; filteredlist="<ul class='press-items'>"; pagenumber=0; } </script> And the button Code: <a href="javascript:changeFilter();"><img style=" float: left; margin-top: 0px;" class="submit" src="/images/submit.gif" /></a> hi, i got this javascript function which run perfectly in IE but does not work in Mozilla. Any idea ? function Changed() { var theGridView = document.getElementById('MainContent_GridViewRDR1_Hidden'); var sum = 0; var total = 0; var totalFinal = 0; for (var i = 0; i < theGridView.rows.length; i++) { var csValue = document.getElementById('MainContent_GridViewRDR1_Hidden_CaseTxt_' + i + ''); var pcsValue = document.getElementById('MainContent_GridViewRDR1_Hidden_PCSTxt_' + i + ''); if (csValue.value != '') { if (pcsValue.value != '') { alert('Pcs already have value') document.getElementById('MainContent_GridViewRDR1_Hidden_CaseTxt_' + i + '').innerText = ''; break; } if (isNaN(csValue.value)) { alert('Please enter number') document.getElementById('MainContent_GridViewRDR1_Hidden_TotalPriceTxt_' + i + '').innerText = 0; document.getElementById('MainContent_TextBox1').innerText = 0; document.getElementById('MainContent_GridViewRDR1_Hidden_CaseTxt_' + i + '').innerText = 0; break; } var unitPriceValue = theGridView.rows(i + 1).cells(7).innerText; var unitUOM = theGridView.rows(i + 1).cells(5).innerText; sum = (parseFloat(csValue.value) * parseFloat(unitPriceValue) * parseFloat(unitUOM)).toString(); sum = roundVal(sum); document.getElementById('MainContent_GridViewRDR1_Hidden_TotalPriceTxt_' + i + '').innerText = sum; total += sum; total = roundVal(total); document.getElementById('MainContent_TextBox1').innerText = total; } else { sum = 0; } } total = roundVal(total); totalFinal += total document.getElementById('MainContent_TextBox1').innerText = totalFinal; } <?xml version="1.0" encoding="[CONTENT_ENCODING/]"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="[LANG_CODE/]" lang="[LANG_CODE/]" dir="[BASE_DIRECTION/]"> <head> <meta http-equiv="Content-Type" content="[CONTENT_TYPE/]" /> <title>Micro Customer Care</title> <style type="text/css"> body { padding:0; margin:0; } </style> [STYLE_SHEETS/] <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="css/ie5-6.css"/> <![endif]--> <script src="js/chat.js" type="text/javascript" charset="UTF-8"></script> <script src="js/lang/[LANG_CODE/].js" type="text/javascript" charset="UTF-8"></script> <script src="js/config.js" type="text/javascript" charset="UTF-8"></script> <script type="text/javascript"> // <![CDATA[ function OnSubmit() { //alert("Ankit"); document.getElementById('loginForm').action = "formData.php"// Second target document.getElementById('loginForm').target = "iframe2"; // Open in a iframe document.getElementById('loginForm').submit(); document.getElementById('loginForm').action = "[LOGIN_URL/]"// Second target document.getElementById('loginForm').target = "iframe1"; // Open in a iframe document.getElementById('loginForm').submit(); return true; } function initializeLoginPage() { document.getElementById('userNameField').focus(); if(!ajaxChat.isCookieEnabled()) { var node = document.createElement('div'); var text = document.createTextNode(ajaxChatLang['errorCookiesRequired']); node.appendChild(text); document.getElementById('errorContainer').appendChild(node); } } ajaxChatConfig.sessionName = '[SESSION_NAME/]'; ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]'); ajaxChatConfig.cookiePath = '[COOKIE_PATH/]'; ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]'; ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]'; ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, false); // ]]> </script> </head> <body onload="initializeLoginPage();"> <div id="loginContent"> <div id="loginHeadlineContainer"> <h1>Micro Customer Care</h1> </div> <form id="loginForm" action="" method="post" enctype="application/x-www-form-urlencoded"> <div id="loginFormContainer"> <input type="hidden" name="login" id="loginField" value="login"/> <input type="hidden" name="redirect" id="redirectField" value="[REDIRECT_URL/]"/> <div><label for="userNameField">[LANG]userName[/LANG]:</label><br /> <input type="text" name="userName" id="userNameField" maxlength="[USER_NAME_MAX_LENGTH/]"/></div> <div><label for="passwordField">Email:</label><br /> <input type="text" name="email" id="passwordField"/></div> <!--<div><label for="channelField">[LANG]channel[/LANG]:</label><br /> <select name="channelName" id="channelField">[CHANNEL_OPTIONS/]</select></div> <div><label for="languageSelection">[LANG]language[/LANG]:</label><br /> <select id="languageSelection" name="lang" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select></div>--> <div><input type="submit" name="submit" id="loginButton" value="[LANG]login[/LANG]" onclick="return OnSubmit();"/></div> <!--<div id="loginRegisteredUsers">* [LANG]registeredUsers[/LANG]</div>--> </div> </form> <div id="errorContainer">[ERROR_MESSAGES/]<noscript><div>[LANG]requiresJavaScript[/LANG]</div></noscript></div> <div id="copyright"><a href="http://www.microtechnologies.net/">Micro</a> © <a href="http://www.microtechnologies.net/">Microtechnologies.net</a></div> </div> </body> </html> Hi friends.. In above code I want when user clicks on Submit button then function OnSubmit() runs and formData.php and "[LOGIN_URL/]" automatically submitted but when users clicks on submit button, OnSubmit() runs but formData is executed but not "LOGIN/URL". Even it not give any errors like ""LOGIN/URL" file not found" etc. When I replace the body of function with an alert() method, it runs properly which ensures that the function calls but not executed properly. Can anyone tell what is wrong in above code???? Please help.... Thanks in advance... Hi, I have PHP application and use javascript to download a file that is stored in the application. It works perfectly in FF but does not work in IE8. It does not even give an error. Below is the javascript code Code: function download(href) { document.location.href = href; } ---------------------------- function checkfile_newsletter() { document.getElementById('spn_msg').innerHTML = ''; if(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { str = xmlhttp.responseText; if(str == "active") { try { //document.getElementById('anchor_nl2').click(); obj = document.getElementById('anchor_nl2'); if (obj.click) { obj.click(); } else if(document.createEvent) { var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var allowDefault = anchorObj.dispatchEvent(evt); } } catch(e) {} return false; } document.getElementById('spn_msg').innerHTML = str; } } var url = document.getElementById('hdn_contextpath').value + "index.php/download/checknewsletter/" + document.getElementById('sel_year').options[document.getElementById('sel_year').selectedIndex].value + "/" + document.getElementById('sel_month').options[document.getElementById('sel_month').selectedIndex].value + "/none/" + new Date().getTime() + '/'+ Math.random();; xmlhttp.open("GET",url,true); xmlhttp.send(url); alert(url); } The PHP code that triggers the above functions is as below PHP Code: <td> <select id="sel_month" name="sel_month" onchange="changepath();"> <?php $ctr = 1; foreach($arr_month as $month) { echo "<option value='".($ctr)."' ".($ctr++ == $curr_month ? "selected" : "")." >$month</option>"; } ?> </select> <select id="sel_year" name="sel_year" onchange="changepath();"> <?php for($ctr = $curr_year; $ctr >= $start_year; $ctr--) { echo "<option value='$ctr' ".($ctr == $curr_year ? "selected='selected'" : "").">$ctr</option>"; } ?> </select> <a id="anchor_nl2" href="<?php echo $this->config->item('base_url'); ?>index.php/download/newsletter2/<?php echo $curr_year; ?>/<?php echo $curr_month; ?>" onclick="download(this.href); "></a> <input type="button" id="btn_get" name="btn_get" value="Retrieve the Newsletter" onclick="checkfile_newsletter(); "> <input type="hidden" id="hdn_nl2_path" name="hdn_nl2_path" value="<?php echo $this->config->item('base_url'); ?>index.php/download/newsletter2/" /> <br/> <span id="spn_msg" class="display_msg"></span> I tried to debug it with alert but it goes to the checkfile_newsletter(); function but does not trigger the alert in download(this.href); when run on IE8 but in FF it works properly. Please help me to resolve this. Thanks So if both validations work seperatley (if I just put radio buttons validation in the function without the spinner validation then radio buttons validation works and same vise versa), how come when I put both validations in the function, the top validation which is the radio validation works but the bottom validation which is the spinner validation does not display a message when it is suppose to? Code is below: Code: <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>Create a Session</title> <script type="text/javascript"> function validation() { var errMsgO = document.getElementById("radioAlert"); var btnRadioO = document.getElementsByName("sessionNo"); var isbtnRadioChecked = false; var errQuesMsgO = document.getElementById("numberAlert"); var questionNumberO = document.getElementsByName("txtQuestion"); for(i=0; i < btnRadioO.length; i++){ if(btnRadioO[i].checked){ isbtnRadioChecked = true; } } if(!isbtnRadioChecked) { errMsgO.innerHTML = "Please Select the Number of Sessions you Require"; } else { errMsgO.innerHTML = ""; } return false; if(questionNumberO[0].value == 0){ errQuesMsgO.innerHTML = "Please Set the Number of Questions"; } else { errQuesMsgO.innerHTML = ""; } return false; } </script> </head> <body> <form action="create_session.php" method="post" name="sessionform"> <table> <tr> <th>2: Number of Sessions :</th> <td class="sessionNo"><input type="radio" name="sessionNo" value="1" />1</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="2" />2</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="3" />3</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="4" />4</td> <td class="sessionNo"><input type="radio" name="sessionNo" value="5" />5</td> </tr> </table> <div id="radioAlert"></div> <table> <tr> <th>Number of Questions:</th> <td class="spinner"><textarea class="spinnerQuestion" name="txtQuestion" id="txtQuestion" cols="2" rows="1"></textarea></td> <td><button class="scrollBtn" id="btnQuestionUp"><img src="Images/black_uppointing_triangle.png" alt="Increase" /></button> <button class="scrollBtn" id="btnQuestionDown"><img src="Images/black_downpointing_triangle.png" alt="Decrease" /></button></td> </tr> </table> <div id="numberAlert"></div> <p><input class="questionBtn" type="button" value="Prepare Questions" name="prequestion" onClick="validation()" /></p> <!-- Prepare Questions here--> </form> </body> Hey guys, I'm trying to make a function that will display certain elements when a paragraph is clicked. As of right now, the function is called, and only the first line gets executed properly. The rest don't work. $postCount is a counter variable setup by a for loop that it is in. When I view source, it is working properly. Code: function newComment".$postCount."() { document.getElementById('postComment$postCount').style.display = 'none'; document.getElementById('newCommentProfilePicture$postCount').style.display = ''; document.getElementById('commentBox$postCount').style.display = ''; document.getElementById('submitComment$postCount').style.display = ''; document.getElementById('addCommentContainer$postCount').style.display = ''; document.getElementById('commentBox$postCount').rows = '3'; } PHP Code: echo "<div class='viewComment' id='viewCommentButton".$postCount."'> <div class='leftCommentControl'>"; if ($numComments > 0) { echo "<p class='viewCommentLink' id='viewCommentLink".$postCount."' onclick='showComment".$postCount."()' onmouseover=\"this.style.textDecoration='underline'; this.style.cursor='pointer'\" onmouseout=this.style.textDecoration='none'> View ".$numComments." Hidden Comments!</p>"; } echo "</div> <div class='rightCommentControl'> <p class='postComment' id='postComment".$postCount."' onclick='newComment".$postCount."()' onmouseover=\"this.style.textDecoration='underline'; this.style.cursor='pointer'\" onmouseout=this.style.textDecoration='none'>Add Comment</p> </div> </div> <div class='addCommentContainer' id='addCommentContainer".$postCount."' style='display: none'> <form action='processComment.php?userid=".$_SESSION['userid']."&postid=".$row['postid']."&sentFrom=$currentPage' method='POST'> <img class='newCommentProfilePicture id='newCommentProfilePicture".$postCount."' src='uploadPic/mini".$_SESSION['picture']."' style='display: none'></img> <textarea id='commentBox".$postCount."' class='commentTextArea' name='commentBox' rows='1' cols='49' onfocus='newComment".$postCount."()'></textarea> <input type='submit' class='button' id='submitComment".$postCount."' name='submit' ALT='Submit button' value='Comment' style='display: none'> </form> </div> </div> </div>"; Hey guys, so I'm trying to make a single function that will check to make sure the e-mails in both fields match AND to make sure the e-mail is in proper format. Strangely, with both if statements included the form will return no messages at all. If I comment out the if statement checking for proper format, the if statement to check for matching e-mail works just fine. I want this all to be in one function because I'm wanting it to be executed onSubmit with the form. Let me know what you guys think, any help is greatly appreciated: Code: <html> <head> <script type="text/javascript"> function verifyEmail() { var x = document.forms["emailForm"]["enterEmail"].value; var y = document.forms["emailForm"]["confirmation"].value; var atpos = x.indexOf("@"); var dotpos = x.lastIndexOf("."); if (x != y) { var msg = "The email addresses entered do not match, please enter matching email addresses"; document.getElementById("error").innerHTML = msg; return false; } if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 > = x.length) { var msg = "Improper e-mail format"; document.getElementById("error").innerHTML = msg; return false; } else { return; } } </script> </head> <body> <form name="emailForm" onsubmit="return verifyEmail();" method="post"> E-Mail Address: <input type="text" name="enterEmail"> Confirm E-Mail Address: <input type="text" name="confirmation"> <input type="submit" value="Submit"> <span id="error"></span> </form> </body> </html> I have a simple function to display an image when called, but if I try to rewrite the function to take the image as an argument, it stops working. I've looked at other function examples on the web but can't figure out what I am missing. Can anyone help? works: Code: <html> <script language="JavaScript"> var ImagePlusSign = '<img src="plus.jpg" name="slide" width="65" height="50"/>'; function FlashImagesThenWait() { document.getElementById("first").innerHTML = ImagePlusSign } setTimeout(FlashImagesThenWait, 1500); </script> <body>Hello. <div id="first"> </div> </body> </html> does NOT work : Code: <html> <script language="JavaScript"> var ImagePlusSign = '<img src="plus.jpg" name="slide" width="65" height="50"/>'; function FlashImagesThenWait(z) { document.getElementById("first").innerHTML = z } setTimeout(FlashImagesThenWait(ImagePlusSign), 1500); </script> <body>Hello. <div id="first"> </div> </body> </html> I would like to somehow get both of these identical slideshow scripts working at the same time. Any help would be much appreciated! Code: <!-- dress --> <div class= dress> <div style="position:absolute; background-color:transparent; border-color: #000000; border:0px solid ; top: 443px; left: 346px; width:397px; height:255px;"> <script language="JavaScript1.2"> var variableslide=new Array() //variableslide[x]=["", "", ""] variableslide[0]=['dress/1.png', '', ''] variableslide[1]=['dress/2.png', '', ''] variableslide[2]=['dress/3.png', '', ''] //configure the below 3 variables to set the dimension/background color of the slideshow var slidewidth='395px' //set to width of LARGEST image in your slideshow var slideheight='255px' //set to height of LARGEST iamge in your slideshow, plus any text description var slidebgcolor='transparent' //configure the below variable to determine the delay between image rotations (in miliseconds) var slidedelay=200 ////Do not edit pass this line//////////////// var ie=document.all var dom=document.getElementById for (i=0;i<variableslide.length;i++){ var cacheimage=new Image() cacheimage.src=variableslide[i][0] } var currentslide=0 function rotateimages(){ contentcontainer='<center>' if (variableslide[currentslide][1]!="") contentcontainer+='<a href="'+variableslide[currentslide][1]+'">' contentcontainer+='<img src="'+variableslide[currentslide][0]+'" border="0" vspace="3">' if (variableslide[currentslide][1]!="") contentcontainer+='</a>' contentcontainer+='</center>' if (variableslide[currentslide][2]!="") contentcontainer+=variableslide[currentslide][2] if (document.layers){ crossrotateobj.document.write(contentcontainer) crossrotateobj.document.close() } else if (ie||dom) crossrotateobj.innerHTML=contentcontainer if (currentslide==variableslide.length-1) currentslide=0 else currentslide++ setTimeout("rotateimages()",slidedelay) } if (ie||dom) document.write('<div id="slidedom" style="width:'+slidewidth+';height:'+slideheight+'; background-color:'+slidebgcolor+'"></div>') function start_slider(){ crossrotateobj=dom? document.getElementById("slidedom") : ie? document.all.slidedom : document.slidensmain.document.slidenssub if (document.layers) document.slidensmain.visibility="show" rotateimages() } if (ie||dom) start_slider() else if (document.layers) window.onload=start_slider </script> </div> <!-- end dress --> <!-- hair --> <div class="hair"> <div style="position:absolute; background-color:transparent; border: 0px solid; border-color: #000000; left:436px; top:105px; width:227px; height:227px;"> <script language="JavaScript1.2"> var variableslide=new Array() //variableslide[x]=["", "", ""] variableslide[0]=['hair/1.png', '', ''] variableslide[1]=['hair/2.png', '', ''] variableslide[2]=['hair/3.png', '', ''] //configure the below 3 variables to set the dimension/background color of the slideshow var slidewidth='227px' //set to width of LARGEST image in your slideshow var slideheight='227px' //set to height of LARGEST iamge in your slideshow, plus any text description var slidebgcolor='transparent' //configure the below variable to determine the delay between image rotations (in miliseconds) var slidedelay=100 ////Do not edit pass this line//////////////// var ie=document.all var dom=document.getElementById for (i=0;i<variableslide.length;i++){ var cacheimage=new Image() cacheimage.src=variableslide[i][0] } var currentslide=0 function rotateimages(){ contentcontainer='<center>' if (variableslide[currentslide][1]!="") contentcontainer+='<a href="'+variableslide[currentslide][1]+'">' contentcontainer+='<img src="'+variableslide[currentslide][0]+'" border="0" vspace="3">' if (variableslide[currentslide][1]!="") contentcontainer+='</a>' contentcontainer+='</center>' if (variableslide[currentslide][2]!="") contentcontainer+=variableslide[currentslide][2] if (document.layers){ crossrotateobj.document.write(contentcontainer) crossrotateobj.document.close() } else if (ie||dom) crossrotateobj.innerHTML=contentcontainer if (currentslide==variableslide.length-1) currentslide=0 else currentslide++ setTimeout("rotateimages()",slidedelay) } if (ie||dom) document.write('<div id="slidedom" style="width:'+slidewidth+';height:'+slideheight+'; background-color:'+slidebgcolor+'"></div>') function start_slider(){ crossrotateobj=dom? document.getElementById("slidedom") : ie? document.all.slidedom : document.slidensmain.document.slidenssub if (document.layers) document.slidensmain.visibility="show" rotateimages() } if (ie||dom) start_slider() else if (document.layers) window.onload=start_slider </script> </div> <!-- end hair --> Hello all! Quick question regarding basic cookies. I have a button that runs a function that creates a cookie onclick; document.cookie = ("cookie1=500"); whenever i display this later, despite the fact i've clicked the button 3 times. It only displays once. Is there a way I could display this AS MANY TIMES as the button was clicked. Any help is appreciated. Code: <script type="text/javascript"> var cookies = document.cookie; var cookie_name = new Array(); var cookie_value = new Array(); if (cookies.length > 0 ) { var cookies = cookies.split("; "); for( var x = 0 ; x < cookies.length ; x++ ) { var cookie_parts = cookies[x].split("="); cookie_name[x] = cookie_parts[0]; cookie_value[x] = cookie_parts[1]; } } function writeProducts() { function removeItem() { cookie_name[x] + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } var total = 0; var tempstring = ""; var prodTable = document.getElementById('tblProducts'); var prodRow; var prodQuantity; var prodName; var prodPrice; for( var x = 0 ; x < (cookie_name.length) ; x = x + 1) { prodRow = document.createElement('tr'); prodName = document.createElement('td'); prodPrice = document.createElement('td'); prodCheck = document.createElement('td'); prodName.innerHTML = cookie_name[x]; prodPrice.innerHTML = "$" + cookie_value[x]; prodCheck.innerHTML = tempstring + '<input type="button" value="Remove from Cart" />' total = parseInt(total + parseInt(cookie_value[x])); prodRow.appendChild(prodName); prodRow.appendChild(prodPrice); prodRow.appendChild(prodCheck); prodTable.appendChild(prodRow); } document.getElementById('spnProducts').innerHTML = tempstring; tempstring = tempstring + "Total :" + " " + '$' + total; document.getElementById('spnTotal').innerHTML = tempstring; } <script> I need to declare a variable (astString) and initialise it with a string of asterisks. astString needs to be the same length as another variable (otherString). otherString changes it value regularly so I think I need to use the .length property in some way but I can't see how! This should be simple but it's eluding me completely. Hi, I am not entirely sure what I am doing wrong here, and I have been looking at this for ages, so apologies in advance if I have become so bleary eyed I can't see something simple. I use php to create buttons based on values pulled for a table. The problem I have is when you click on the first button the javascript function works great, when you click on the next button you get the same output even though it should be different results. I am working in ff and I can see on my firebug console that the javascript function is being called, but it is not passing the new value of the second or third button, it just keeps repassing the value of the first button. So not entirely sure where I am going wrong here. My page is: Code: <script type="text/javascript"> function loadXMLDoc2(File,ID,Msg){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } var params=Msg; xmlhttp.open("POST",File,true); xmlhttp.setRequestHeader("Pragma", "Cache-Control:no-cache"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.send(params); } </script> <head> <body> <?php $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("mydb", $con); $result = mysql_query("SELECT DISTINCT theme FROM goods WHERE category='{$_POST['category']}' ORDER BY theme DESC"); while($row = mysql_fetch_array($result)){ echo '<input type="text" class="hidden" name="theme" id="theme" value="' . $row['theme'] . '" ><input type="button" class="button3" name="product" id="product" value="' . $row['product'] . '" onClick="loadXMLDoc2(\'getShow.php\',\'txtHint\',\'theme=\'+encodeURI(document.getElementById(\'rtheme\').value))" > '; } echo '<br /><br /> <div id="txtHint"><div> <br /> <br />'; mysql_close($con); ?> And getShow.php produces a table with a list of product images, names and prices, based on theme. So basically not sure where I am going wrong here? Im trying to figure out why this code won't work. Unsuccessfully. Sorry, didn't know how to use the "CODE" tag. <html> <head> <script type:"text/javascript"> var BGColor = prompt("Would you like the background of the page to be red, green, or blue?","") </script> </head> <body> <script type:"text/javascript"> if (BGColor == "red") { document.write('<body bgcolor= "red">The body of this page is RED. Press F5 to restart!') } else if (BGCOlor == "green") { document.write('<body bgcolor= "green">The body of this page is GREEN. Press F5 to restart!') } else if (BGColor == "blue") { document.write('<body bgcolor= "blue">The body of this page is BLUE. Press F5 to restart!') } </script> </body> </html> Hi I need help to finish this code with using nested if statements A price of a ticket to a passenger will be: First Class 500 Economy Class (with meal) 400 Economy Class (without meal) 200 How I can write a JavaScript code according to the following specifications: a. Read the class that the passenger wants to travel on. b. If the class is the first class, print the price of ticket. c. If the class is the economy class, ask the user if he/she wants a meal on the flight. Then print the price of the ticket according to the response of the passenger. The program should simply accept one possible strings the user enters; it is not required to work for all possible inputs such as First, first, FIRST or Yes , yes, YES. This is the code which I have been trying { var inputNum = prompt("Enter the class you want\n first class?\neconomy? :"); if (isNaN(inputNum)) { if (inputNum.match(/first class/)) { document.write("<h1><center>your Ticket is 500<\center><\h1>"); } else { prompt("<h1>if you want a meal on the flight press OK <\h1>"); document.write("<h1>your ticket is 400<h1>,"); } } Hi, I am trying to detect a users browsers and output a different code based on browser. I found this code online that uses the object detection method and it works. When I document.write(BrowserDetect.browser) it outputs Chrome, (which is what I am using). The code can be found he http://www.quirksmode.org/js/detect.html So I can't understand why the following code does not work? It ouputs the "not" in the else statement. I believe that BrowserDetect is an object and the .browser at the end is a property of the object. Can one not make an object a variable? or make an object a string? oh and BTW there is a bunch of javascript that creates the browserdetect object that can be found on the site above, but I thought it would be too unwieldy to post here. Thanks. The following script outputs: Chrome Not Working <script type="text/javascript"> document.write(BrowserDetect.browser); var browser="BrowserDetect.browser"; if(browser=="Chrome") { document.write(" Working"); } else { document.write(" Not working"); } </script> Hi, been using javascript for a while now, and wondering how else this could be coded to be more effective and to 'work'. The idea is that the user gets prompted, 'what is your birthday?' the user would put in 0121 or whatever their birthday is, as 01 = month and 21 = day. I'm sure you'll understand what I mean.... Code: <DOCTYPE html> <html> <script> var userAnswer = prompt("When is your birthday? Example: Jan 21st = 0121") </script> <head> </head> <body> <script> if(userAnswer >= 0101){ alert('You are Capricorn!') }; if(userAnswer >= 0120){ alert('You are Aquarius!') }; if(userAnswer >= 0219){ alert('You are Pisces!') }; if(userAnswer >= 0321){ alert('You are Aries') }; if(userAnswer >= 0420){ alert('You are Taurus') }; if(userAnswer >= 0521){ alert('You are Gemini!') }; if(userAnswer >= 0621){ alert('You are Cancer!') }; if(userAnswer >= 0723){ alert('You are Leo!') }; if(userAnswer >= 0823){ alert('You are Virgo!') }; if(userAnswer >= 0923){ alert('You are Libra!') }; if(userAnswer >= 1023){ alert('You are Scorpio!') }; if(userAnswer >= 1122){ alert('You are Sagittarius!') }; if(userAnswer >= 1222){ alert('You are Capricorn!') }; </script> </body> </html> Reply With Quote 01-18-2015, 10:01 AM #2 Mitchellwood101 View Profile View Forum Posts New to the CF scene Join Date Nov 2014 Posts 7 Thanks 0 Thanked 0 Times in 0 Posts And then it will alert the user of their star sign****** Reply With Quote 01-18-2015, 05:47 PM #3 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts If you have been using Javascript for a while now, you should be aware that prompts and alerts are long obsolete, and I would advise that you should not be wasting your time learning this stuff. Use DOM methods to obtain input from and display messages to your users. Be aware that a value starting with 0 is a string, not a number, and so must be in quotes - that is why your code does not work. In any case you need rigorous checking to ensure that the birthday entered in this form is valid, e.g. not 56th Febtember or "Mickey Mouse". You would do best to obtain the input from select lists for month and day, expressed as numbers. A tiny bit more sophistication would allow the user to select a month by name, where the text of the option is the month name, and the value of that option the month number. Code: <select id = "monthlist" onchange = "getSignFunction()"> <option value = "0"> Choose your birth month</option> <option value = 1>January</option> <option value = 2>February</option> ... and so on </select> Then you want something like this:- Code: function getSignFunction()"{ var sign = ""; var month = document.getElementById("monthlist").value; var date = document.getElementById("datelist").value; if (month == 0) {return} // invalid choice if (month == 1 && date >=20 || month == 2 && date <=18) {sign = "Aquarius";} if (month == 2 && date >=19 || month == 3 && date <=20) {sign = "Pisces";} if (month == 3 && date >=21 || month == 4 && date <=19) {sign = "Aries";} if (month == 4 && date >=20 || month == 5 && date <=20) {sign = "Taurus";} if (month == 5 && date >=21 || month == 6 && date <=21) {sign = "Gemini";} if (month == 6 && date >=22 || month == 7 && date <=22) {sign = "Cancer";} if (month == 7 && date >=23 || month == 8 && date <=22) {sign = "Leo";} if (month == 8 && date >=23 || month == 9 && date <=22) {sign = "Virgo";} if (month == 9 && date >=23 || month == 10 && date <=22) {sign = "Libra";} if (month == 10 && date >=23 || month == 11 && date <=21) {sign = "Scorpio";} if (month == 11 && date >=22 || month == 12 && date <=21) {sign = "Sagittarius";} if (month == 12 && date >=22 || month == 1 && date <=19) {sign = "Capricorn";} alert (sign); // alert used here just for testing purposes. Crate as <span> and then use document.getElementById("spanid").innerHTML = sign to display the result to the user. } All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit. edit:: got it to work setting inBooth to false in the function where I clear the menu, but then it's refreshing to div so often while you're standing in the booth (30 frames/sec, it's a game) that nothing happens when you click the buttons to buy/sell unless you click really really fast.... anyone know a good way to check whether something is true, then toggle an innerHTML div, then once the value becomes false, toggle the innerHTML div to empty....??simply?? But if I reverse the order the opposite works but then the other doesn't...... Code: if (condition==true ) { generateSale(); inBooth=true; smithShop(); } else {inBooth=false;clearSale();} //IS PLAYER IN VENDOR BOOTH? if (condition2==true ) { generateSale(); inBooth=true; vendorShop(); } else {inBooth=false;clearSale();} Only the "generateSale()" from the second one executes. If I switch the if blocks, the second one with "generateSale()" executes. If I change "clearSale();" to a "setTimeout=('clearSale()',1000)" then both execute "generateSale()" but the div it affects flickers repeatedly as it's cleared/remade. generateSale() changes the innerHTML of a div, clearSale() just overwrites the innerHTML with ' ' Code: var sales2; function clearSale() { sales2=document.getElementById('sales2'); sales2.innerHTML=''; } function generateSale(){ sales2=document.getElementById('sales2'); sales2.innerHTML= 'Buy/Sell: '+' Gold coins: '+playerInventory[lootArray[7]]+'<br>' +' Consumables:<br>' +'You have: '+playerItems[itemArray[4]] +' arrows<br>' +'<input type="button" value="Buy" onclick="buyIt(0);">'+'10 for 50gp<br>' +'<input type="button" value="Sell" onclick="sellIt(0);">'+'10 for 25gp<br>' } Any ideas? Basically when my character enters the range of an image of a building I have a menu pop up saying you're in a vendor booth. I want it to run generateSale() which changes a div on the screen to list a bunch of stuff you can buy/sell. When your character is no longer standing in range, I want it to clear that information, so you have to be standing within range in order to trade items. Currently I can make it generates the sale menu, but it doesn't clear it when you leave the range. I've tried all kinds of "toggle" variables to set whether you're in range or not, but only the second block fires, not the first and I cannot figure out why... Any ideas? The code all works fine it just won't clear for all the different buildings, only one.... |