JavaScript - Function Only Works Once
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 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 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 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 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> 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>"; 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, 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> 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? Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> Hi All, I'm trying to convert an anonymous function to a real function (nesting is getting out of hand), however the msg object becomes undefined after conversion. Here is the converted anonymous function which fails: https://gist.github.com/2587613 and here is the original anonymous function which works: https://gist.github.com/2587667 Any help would be greatly appriciated <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function convert(num, dec){ var val = document.getElementById("fromVal").value; if(isNaN(val)){ return } function roundNumber(num, dec) { var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec); return result; } document.getElementById("toVal").value = val * metrics[document.getElementById("fromSystem").value]/ metrics[document.getElementById("toSystem").value]; } var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <table> <tbody> <tr> <td><input id="fromVal" style="width: 100px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="fromSystem" onchange="convert()"> <option value="mm">millimeters</option> <option selected="selected" value="cm">centimeters</option> <option value="m">meters</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></td> </tr> <tr> <td colspan="1" align="center">=</td> </tr> <tr> <td><input id="toVal" style="width: 100px;" type="text" disabled="disabled" /><select id="toSystem" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">meters</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></td> I found this script, and it works great: Code: <script type="text/javascript"> function disable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","true"); } } </script> I tried to make the inverse by simply reversing the setAttribute() like so: Code: <script type="text/javascript"> function enable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","false"); } } </script> But that didn't do it. Can someone show me why, and how to fix it? Here's the sample form which I'm trying to test it on: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> disable<br/> <input type="radio" name="test" onclick="enable('D1')" /> enable<br/> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /><br/> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /><br/> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /><br/> </fieldset> </form> Edit: The ultimate goal which I'm working toward now (step by step =) is to have a form more like: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /> </fieldset> <input type="radio" name="test" onclick="disable('D2')" /> <fieldset id="D2"> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /> </fieldset> <input type="radio" name="test" onclick="disable('D3')" /> <fieldset id="D3"> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /> </fieldset> </form> And have the fieldsets enable and disable according the selection of the radio buttons. Also, the fieldsets (and their ID's) will be dynamically generated via PHP Thanks-a-bunch, ~ Mo I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? Code: <html> <head> <title>TESTING</title> <script type="text/javascript"> <!-- document.write("<input type='submit' value='submit' onclick='func()'>"); function func() { document.write("<input type='submit' value='New Button' onclick='func()'>"); window.alert("THIS"); } --> </script> </head> <body> <!--input type="button" value="Read" onclick="ReadFiles()"--> </body> </html> This is a very basic version of what I am trying to do. I have a dynamic list which is set in a table. When clicked, a function is run to set up a new list.. The reason I explain that, is that I need to keep it dynamic. Now for the problem: When I run this page, I have the button made right away, then when clicked it creates the new button. The new button should also run the function to create the new button again, but when I click it, I only receive "error on page". I don't know if there is a better way to go about this, but as for this route, I am stuck. Any help is greatly appreciated! -Shane I made a mouseover event of a caption on a picture, when I hover the opacity of the background color of the hover and the text goes down. What I want is that when I hover over the image which the caption is floating on, the onmouseover event gets activite. For an imaginary example: Code: function unhighlight(x) { x.style.backgroundColor="transparent" } Function ActivationFuction() { activate.function="unhighlight" } thanks |