JavaScript - What's Wrong With This Function?
I put the following line in the onchange tag of a listbox to use the values to manipulate an iframe:
document.getElementById('viewer').src=('Location_Files/')+(this.value)+('.htm') There it works perfectly but I wanted to do more so I decided to build a function around it: function display() { document.getElementById('viewer').src=('Location_Files/')+(this.value)+('.htm') } When I put the function in the onchange tag instead, the iframe tries to work but I get a "can't load page" message like the src is broken. Now when I first made that line it took me hours to figure out that I can't use a "\" because if I do it fails. So I went with "/" and that works but I wonder if that rules change when I specify it in the java script instead of in the onchange tag itself. Either way it still breaks if I try to use "\". Does anyone see the problem? Similar TutorialsI can't get the function getchecked() to show an alert box... Code: <script> function getCheckedValue(radioObj) { if(!radioObj){ return ""; } var radioLength = radioObj.length; if(radioLength == undefined){ if(radioObj.checked){ return radioObj.value; }else{ return ""; } } for(var i = 0; i < radioLength; i++) { if(radioObj[i].checked) { return radioObj[i].value; } } return ""; } } function getchecked(){ var thecode=getCheckedValue(document.forms['radioExampleForm'].elements['code']); if(thecode!==""){ if(thecode=="HTML"){ alert('Checked value is: '+thecode+'.'); //playSound("test1.mp3"); }else if(thecode=="PHP"){ //playSound("test2.mp3"); alert('Checked value is: '+thecode+'.'); }else{ //playSound("test3.mp3"); alert('Checked value is: nothing'); } } } </script> <label for="code1"><input type="radio" value="HTML" name="code" id="code1"> HTML</label> <br><label for="code2"><input type="radio" value="PHP" name="code" id="code2"> PHP</label> <br><label for="code3"><input type="radio" value="MySQL" name="code" id="code3"> MySQL</label> <br><input type="button" onclick="getchecked()" value="Show Checked Value"> thanks! Hey there, I started learning Javascript about five weeks ago when I started my University course, and I have been doing above averagely in the little mini-tests, but now I am on coursework I have been having trouble getting past the most simple thing, and I can't help think that I'm just approaching the issue from the wrong angle in my head. I'm not asking to be spoon-fed the answers from veteran coders or cheating because that just defeats the point of learning. In fact I actively discourage anyone from posting a direct answer to this question. However I would like some assistance in the kind of thinking that would help me in term of creating a function like this; Name of function and parameters: index(string,pattern,caseSensitive) "Where pattern starts in string (or -1 if it is not found), return the index. The search needs to be case sensitive if the third parameter is true else it is case insensitive." (Where underlined and italics are parameter names) I know how to create functions in general, however I cannot get my head around the fact that the parameters are supposed to represent something, and it is required for me to program something without knowing what the parameters represent. I know it's simple and I'm probably thinking about it the wrong way. If anyone could assist me I would be grateful. So I want this function to return the date in the format: 4-Jan-2011. I feel like I have to make the variables strings or something but I can't figure it out, I'm kinda new to javascript. Code: function calander(TheDay) { var theDate = new Date(); var day = new theDate.getDay(); var month = new theDate.getMonth(); var year = new theDate.getFullYear(); if (month == 0) {month = "Jan";}if (month == 1) { month = "Feb"; } if (month == 2) { month = "March"; }if (month == 3) { month = "April"; } if (month == 4) { month = "May"; }if (month == 5) { month = "June"; } if (month == 6) { month = "July"; }if (month == 7) { month = "Aug"; } if (month == 8) { month = "Sept"; }if (month == 9) { month = "Oct"; } if (month == 10) { month = "Nov"; }if (month == 11) { month = "Dec"; } TheDay.value = day + "-" + month + "-" + year; } HTML CODE BELOW (JAVASCRIPT CODE FOLLOWS); Code: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>Text Object value Property</title> <script type="text/javascript" src="../jsb-global.js"></script> <script type="text/javascript" src="jsb-11-02.js"></script> </head> <body> <h1>Text Object value Property</h1> <form id="UCform" action="make-uppercase.php"> <p> <input type="text" id="converter" name="converter" value="sample"> </p> </form> </body> </html> This program below switches what is entered into the text filed to caps when hitting the enter button or the tab button. Can someone explain to me why it is not working. The answer would be helpful to a newbie who's trying hard to learn the fundamentals... Code: // initialize when the page has loaded window.onload = initialize; var oInput; // (global) input field to make uppercase // apply behaviors when document has loaded function initialize() { // do this only if the browser can handle DOM methods if (document.getElementById) { // apply event handler to the button oInput = document.getElementById('converter'); if (oInput){ var event = oInput.onchange; upperMe(event); } // apply event handler to the form var oForm = document.getElementById('UCform'); if (oForm) { var event = oForm.onsubmit; upperMe(event); } } } // make the text UPPERCASE function upperMe(evt) { // consolidate event handling if (!evt) evt = window.event; // set input field value to the uppercase version of itself var sUpperCaseValue = oInput.value.toUpperCase(); oInput.value = sUpperCaseValue; // cancel default behavior (esp. form submission) // W3C DOM method (hide from IE) if (evt.preventDefault) evt.preventDefault(); // IE method return false; } I need some help on my math equation, I got the calculations and confirm.submit, and the alert messages to all work properly, but when I go to put the data into the math equation, I am coming up with some outrageous number way off from what it is supposed to be. What I am trying to accomplish is to take the calculated number of day and hours and minutes; multiply the total time in hours by the equipment cost per hour and calculate the total amount of rent. My problem I think is in the calculate total amount of rent section in the script. Please help, your expertise is greatly appreciated. Below is the math equation in the script section: Code: //calculate days from date field function checkit() { var today = new Date(); var nowyear = today.getFullYear(); var d1 = document.forms[0].pickupDate.value.split("/"); var yr = d1[2]; var mm = d1[0]-1; var dy = d1[1]; var OK1 = checkValidDate(yr,mm,dy); if ((yr < nowyear || yr > nowyear +1)) {OK1 = false} // only valid for current year and next year var d2 = document.forms[0].returnDate.value.split("/"); yr = d2[2]; mm = d2[0]-1; dy = d2[1]; var OK2 = checkValidDate(yr,mm,dy); if ((yr < nowyear || yr > nowyear+2)) {OK2 = false} if ((!OK1) || (!OK2)) { alert ("Invalid dates\(s\) or incorrect format! Please try again."); document.forms[0].pickupDate.value = ""; document.forms[0].returnDate.value = ""; return false; } // arbitrary or example start and end times obtained from elsewhere (select lists) var fhrs = parseFloat(document.forms[0].pickupHours.value); var fmins = parseFloat(document.forms[0].pickupMinutes.value); var shrs = parseFloat(document.forms[0].returnHours.value); var smins = parseFloat(document.forms[0].returnMinutes.value); var firstDate = new Date(d1[2],d1[0]-1,d1[1],fhrs,fmins); // note month must be 0-11!! Also note USA date format var secondDate = new Date(d2[2],d2[0]-1,d2[1],shrs,smins); var difference = secondDate.getTime() - firstDate.getTime(); var secs = difference/1000; var days = Math.floor(secs/86400); secs %= 86400; var hours= Math.floor(secs/3600); if (hours<10) {hours = "0" + hours} secs %= 3600; var mins = Math.floor(secs/60); if (mins<10) {mins = "0" + mins} alert ("Time Difference is " + days + " Days " + hours + " Hours " + mins + " Minutes"); //calculate total amount of rent var equip = parseFloat(document.forms[0].equipment.value); var total = (((days * 24) + hours + mins) * equip); var OK = window.confirm(" The total rental cost is $" + total + "\n Click OK to accept, Cancel to decline"); if (OK) {return true} else {return false} } function checkValidDate(yr,mm,dy) { var nd = new Date(); nd.setFullYear(yr,mm,dy); // YYYY,MM(0-11),DD var ndmm = nd.getMonth(); if (ndmm != mm) { return false; } else { return true; } } This is the form in the body section: Code: <form onsubmit = "return validateForm()" action = "mailto:rogalskibf@gmail.com?subject=ABC Customer Reservation" method="post" enctype="text/plain"> <table border = "0"> <tr> <td> Equipment:<br/> <select name = "equipment"> <option value="unselected">Select Equipment Type</option> <option value = 20>Fishing Boat</option> <option value = 15>Kayak</option> <option value = 2>Mountain Bike</option> <option value = 10>Scuba Gear</option> </select> </td> </tr> <tr> <td> Pick-up Date: <br/> <input type = "text" id = "dateIn" name = "pickupDate" id = "date1" onchange = checkValidPDate(this.value)> </td> <td> Pick-up Time: <br/> <select name = "pickupHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "pickupMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> Return Date: <br/> <input type = "text" id = "dateOut" name = "returnDate" id = "date2" onchange = checkValidRDate(this.value)> </td> <td> Return Time: <br/> <select name = "returnHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "returnMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> First Name: <br/> <input type = "text" name = "firstName"/> </td> <td> Last Name: <br/> <input type = "text" name = "lastName"/> </td> </tr> <tr> <td> Street: <br/> <input type = "text" name = "street"/> </td> <td> City: <br/> <input type = "text" name = "city"/> </td> <td> Zip:<br/> <input type = "text" name = "zip" maxlength = "5"/> </td> </tr> <tr> <td> Date of Birth: <br/> <input type="text" name="date" onblur="checkAge(this.value)" /> </td> </tr> <tr> <td colspan = "3" align = "center"> <input type = "submit" name = "submit" value = "Submit Reservation" onclick = "return checkit()"/> <input type = "button" value = 'Set Cookies' onclick = "setCookie('anyName', cookieValue ,expDate)"> <input type = "button" value = 'Display Cookies' onclick = "dispCookie('anyName')"> </td> </tr> </table> </form> Hi, I am doing a Validation for Form "Text input". If the user leaves the input empty, a function is starting to run. If the field is bigger than 1 - so it doesn't get into the function. The problem is: The first time, the user left the input empty, function ran, and I got the alert - that's OK. Second time, The user added 10 in the AGE input - And again he gets the Alert - But he should not. Note: Age input value, returns from a different function (calc) to a var called: result. this is the code: Code: $(document).ready(function(){ $('#btn_send').click(function(){ //var result gets the value from another function of input "Age" value. -> return thisform.Age.value var result = calc(document.getElementById("campaignform")); if (result<1) { $("#campaignform").submit(function(event) { event.preventDefault(); alert ("prevent default"); }); } else{ return true; }; }); }); so if you try the second time to click on Submit, then you get into $('#btn_send').click(function() and eventhough you added for example 67 in the AGE (return as result) input, you get into the IF statement which is: if (result<1) I'm pretty new to developing, so I hop you will understand me. Sorry if I have mistakes. Can you advice what could be a better TITLE for this question? thanks in advance, Shai 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. Hi! 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 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 <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> 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 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> 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 Hi, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> 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 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? Hello again! Is there any way to pass a function(with its parameters) to another function using a parameter? Examples: Here is how I do it now: PHP Code: function output(text){ alert(text); } function bla(text, func){ output(text); } bla("Text is here", output) //Outputs "Text is here" I only want to pass the function to bla() as a parameter. I need something like this: PHP Code: function output(text){ alert(text); } function bla(func){ output(); } bla(output("Text is here")) //Outputs "Text is here" Is this possible in some way? Thanks in advance. |