JavaScript - Problem With Function Parameter
Hi,
I am learning javascript from a book ("Javascript and JQuery Missing Manual") and one example there sets my head spinning and I can't understand how the script works. I'd be very grateful if someone could write a few words about the aspect I don't understand. Basically it is line seven I don't understand. How is the word question tied to the items in the questions array. I understand the 0 and 1 on line eight and nine and why they focus on the first and second item in the sub-array, but still, how can the word question point to the relevant item in the questions array? Code: var score = 0; var questions = [ ['How many moons does Earth have?', 1], ['How many moons does Saturn have?', 31], ['How many moons does Venus have?', 0] ]; function askQuestion(question) { var answer = prompt(question[0], ''); if (answer == question[1]) { alert('Correct!'); score++; } else { alert('Sorry. The correct answer is ' + question[1]); } } for (i=0; i<questions.length; i++) { askQuestion(questions[i]); } Similar TutorialsHello 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. Hi all I'm adding buttons to my google map through a loop. I pass some parameters, and the addButtons() function creates the buttons. How can I pass the "task" for the button to the function? In the addDomListener line below, I'm now writing the function name literally, I'd like find a way with a parameter. Thank you.. Code: // The loop... for (i=0;i<=4;i++) { oCC = addButtons(aCtrls[i],'btnContainerChild'); ... } // The function... function addButtons(cButtonID,cClassName) { var oButton = document.createElement('DIV'); oButton.className=cClassName; oButton.id=cButtonID; //... other settings here... // ===> Here, I'd like to set the click function through a parameter google.maps.event.addDomListener(oButton, 'click', function() {gmapSetCenter(defaultCenter)}); Hey guys, i have a question about my array. I have an array called numberarray with 20 elements and i want it to be accepted into a function as a parameter? But i only want the first 10 to be accepted. Does anyone know exactly how i would go about doing this in my function?
Please advise me: I've successfully called a variety of functions that have no parameter value such as: function expand() //expand() in this line is merely an example But I'm unsuccessful calling a function with a paramter value such as: function expand(id) Here is the the call line: document.addEventListener("DOMContentLoaded", expand(id) , false); Here is the Function: function expand(id) { for (var i = 1; i<=10; i++) { if (document.getElementById('smenu'+i)) { document.getElementById('smenu'+i).style.display='none'; } } if (id) { id.style.display='block'; } } I have a good understanding of javascript although I am new to working xml. So I am having a problem getting javascript to recognize that my parameter value in my function call is an attribute in my xml. I called the js function like this: Code: <a href="#" onClick="ebookCategory(marketing);">Marketing</a> Here is my js function: Code: var category; function ebookCategory(category) { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","ebook.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; document.write("<table border='1'>"); var x=xmlDoc.getElementsByTagName(category); for (i=0;i<x.length;i++) { document.write("<tr><td>"); document.write(x[i].getElementsByTagName("bookCover")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue); document.write("</td><td>"); i++; document.write(x[i].getElementsByTagName("bookCover")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue); document.write(x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue); document.write("</td></tr>"); } document.write("</table>"); } // end ebookCategory() Some of the aspects in this function are new to me, xml stuff. Here is my xml setup: Code: <ebook category="marketing"> <bookCover><img src="/millionaire/ebooks/covers/miracle2.jpg" height="150" width="150" /></bookCover> <title>Marketing Miracle</title> </ebook> I appreciate any help in the matter Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script> window.onload = function(){h = parseInt(document.getElementById( "div1" ).style.height);} var t; function addHeight(openAccordionID){ clearInterval(t); document.getElementById(openAccordionID).style.height = h+"px"; h+=1; t = setInterval("addHeight('"+openAccordionID+"')",10); for(var x=1; x<h; x++) if(h%(x*100)==0){clearInterval(t);} } </script> </head> <body> <div id="div1" onclick="addHeight(this.id)" style="width: 200px; height: 20px; background-color: yellow;">Increase Height</div> </body> </html> How can I still use the parameter "openAccordionID" in the blue-highlighted part? I tried, but it failed. 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> <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> Code: <select class="drop" name="pet Display" id="drop" onChange="if(this.options[this.selectedIndex].value=='a') {document.getElementById('myFieldSet').style.visibility='visible'} else{document.getElementById('myFieldSet').style.visibility='hidden'}if(this.options[this.selectedIndex].value=='b') {document.getElementById('myFieldSet1').style.visibility='visible'} else{document.getElementById('myFieldSet1').style.visibility='hidden'}if(this.options[this.selectedIndex].value=='c') {document.getElementById('myFieldSet2').style.visibility='visible'} else{document.getElementById('myFieldSet2').style.visibility='hidden'}"> i need to fix this function or a different (external is better )with the same results thanxz Hi, In ASP.NET intranet web page have user input. Have 5 check boxes with two attending text boxes for each. The default value for the text boxes is zero and the text boxes are disabled for input. When the user checks a check box the two corresponding text boxes become enabled for input. Have two command buttons - Submit for database posting and Cancel. I set the Cancel button with a js window.confirm, uncheck the check boxes, and reset any input values in the text boxes back to zero. When I tested the code the checked check boxes were unchecked and the first text box holding user input was reset to zero value. However, the other text boxes containing user input values were not reset to zero. I altered the sequence of the code - for example - list the check box then its text boxes and so on. I tried listing the text boxes first then the check boxes. These did not resolve the problem - I was thinking linear execution of the code. Any suggestions to rememdy this? This is the js function: function Empty() { var res=window.confirm("Please confirm cancellation-your input will be cleared"); if(res==true) { document.getElementById("chkDVTT").value=""; document.getElementById("chkLM").value=""; document.getElementById("chkVMB").value=""; document.getElementById("chkVEB").value=""; document.getElementById("chkVUB").value=""; document.getElementById("txtDVTTRegHrs").value="0"; document.getElementById("txtDVTTOTHrs").value="0"; document.getElementById("txtBRLMRegHrs").value="0"; document.getElementById("txtBrLMOTHrs").value="0"; document.getElementById("txtVMBRegHrs").value="0"; document.getElementById("txtVMBOTHrs").value="0"; document.getElementById("txtVEBRegHrs").value="0"; document.getElementById("txtVEBOTHrs").value="0"; document.getElementById("txtVUBRegHrs").value="0"; document.getElementById("txtVUBOTHrs").value="0"; } } Thanks, John Hello, I'm working on my little grabber and now I want to try something in javascript without success, so here my javascript code: PHP Code: //begin ajax grabber function validateGrabber(b_on_submit){ if(document.grabber.keywords.value == '' || document.grabber.keywords.value == 'search'){ alert('You did not enter a search term. Please try again.'); if(b_on_submit == 'true') return false; } else{ document.grabber.btn.submit(); } } function grabber(inputGrabber) { if(inputGrabber.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else if(inputGrabber.length > 2) { $.post(MELODYURL2+'/ajax_grabber.php', {queryString: ""+inputGrabber+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // end ajax grabber and that's my template code: PHP Code: <form action="{$smarty.const._URL}/search.php" method="get" id="search" name="grabber" onsubmit="return validateGrabber('true');"> <input name="keywords" type="text" value="" class="search_keywords" id="inputGrabber" {if $smarty.const._SEARCHSUGGEST == 1}onkeyup="grabber(this.value);" onblur="fill();" autocomplete="off"{/if} /> <input name="btn" value="{$lang.submit_search}" type="submit" class="search_bttn" /> <div class="suggestionsBox" id="suggestions" style="display: none;"> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> </form> the first function doesn't show the alert and the second doesn't work at all... Hi guys I kinda needed help on jQuery/ javascript.. Here's the test page.. http://development.andrewfopalan.com/devpage/test.html# what I'm trying to do is like this.. http://trailers.apple.com/trailers/s...bandofmisfits/ the movie box... so far, I have made the cosmetics.. but the thing I was going to ask was.. when you click on the down arrow.. a popup dropdown list is going to show.. the problem is I am copying the same effect as the one with apple.. when you click outside of the popup dropdown list, the dropdown list should be fading out... but it wouldnt... I tried using doing.. it like this Code: $("#wrap" ).click(function () { $(".dropdown").fadeOut(); }); but the problem is.. whenever I click the down arrow button.. it continues to fadeout.. as soon as it fadesin... how should I do this? please guide me.. everything works just fine.. just this one.. I am really lost.. i the whole jquery code is in the page sirs... please help me pretty new to javascript/jquery.. Hi. Firstly, i apologise for this being a google maps related question but the problem is a regular javascript question i believe, and it's really frustrating me. As i'm sure you're aware that with the maps you can click on a red 'marker' and make an info box pop up. I'm trying to do this with a text link outside of the map. My problem is calling that script via the text link. i really can't see what i'm doing wrong; my html link Code: <a href="javascript;" onmouseover="marker.openInfoWindowHtml();">test</a> and the javascript from the map Code: GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(); }); I'm sure it's something simple but i've been trying variations for hours and I can't get my head around it. Anyone with any ideas would be an absolute star. Cheers, Pat. Hi guys, I'm a bit new to all this javascript and of course I have a problem.. I have searched all the forums and none have helped me fix this problem.. js file: function buildTable (prodNum){ moo = document.GetElementById('showProd').insertRow(0); /*some crap code*/ } html code: <table id = "showProd" border ="3"></table> i keep on recieving from firebug an error saying GetElementById is not a function... any help will be greatly appreciated. thank you. I guess it is because it is 2am and had a few beers but i cannot get this to work and i know its pretty simple to do - see the code below: Code: {if ""|fn_needs_image_verification == true} {assign var="is" value="Image_verification"|fn_get_settings} <p{if $align} class="{$align}"{/if}>{$lang.image_verification_body}</p> {assign var="id_uniqid" value=$id|uniqid} {literal} <script language="javascript" type="text/javascript"> function reloadCaptcha() { captcha = document.getElementById("captureURLID").src; return captcha += 'reload'; } </script> {/literal} {if $sidebox} <p><img id="verification_image_{$id}" class="image-captcha valign" src="{"image.captcha?verification_id=`$SESS_ID`:`$id`&`$id_uniqid`&"|fn_url:'C':'rel':'&'}" alt="" onclick="this.src += 'reload' ;" width="{$is.width}" height="{$is.height}" /></p> {/if} <p><input class="captcha-input-text valign" type="text" name="verification_answer" value= "" autocomplete="off" /> {if !$sidebox} <img id="verification_image_{$id} captureURLID" class="image-captcha valign" src="{"image.captcha?verification_id=`$SESS_ID`:`$id`&`$id_uniqid`&"|fn_url:'C':'rel':'&'}" alt="" onclick="this.src += 'reload' ;" width="{$is.width}" height="{$is.height}" /> {/if} <img src="{$images_dir}/icons/icon_reload.png" height="25" width="25" alt="Reload Captcha Image" onclick="reloadCaptcha();" class="valign image-captcha" /></p> {/if} now the following works totally fine, when you click the captcha code changes..... "onclick="this.src += 'reload'" you will notice i have added a custom reload button image below this with a onclick calling a custom function "reloadCaptcha(); which i want to reload the captcha image above it - however it is not working, i have done the function so it grabs the src from the element ID, i have added 2 ID's to the IMG but cannot remember if you can have multiple IDs or not which if not could be causing the problem but not 100% sure how to include the smarty code for the generated ID on that image. Any ideas on the code above from having a quick glimps? as the code stands i get the error: Error: captureURL is null Many Thanks What I want to do is have a two-dimension array where some of the elements point to the value in another element. I have done this successfully in PHP using referfences (=&) and now I want to do it in JavaScript. My JS skills are limited but I found this post explaining how it can be done - http://stackoverflow.com/a/1687183 Here's the code from that - Code: Function.prototype.toString = function() { return this(); } var x = 1; var y = function() { return x } x++; alert(y); // prints 2 It looks like it will do what I need to do. However, I want to use a two-dimension array, and if I try this it doesn't work - Code: for (var a = 2; a <= 5; a++) for (var b = 1; b < a; b++) matrix[a][b] = function() { return (matrix[b][a]) }; matrix is the two-dimension array which is alreay set up with some values. The two for loops are structured to fill in the rest of the values as references to existing values (it's a 5 x 5 array). The problem is coming from function() { return (matrix[b][a]) } because instead of the values for a and b being used in the creation of the anonymous function the actual variable names are used instead. Then later when I attempt to read one of the values setup by this it is "undefined" because the anonymous function is tries to return matrix[a][b] rather than matrix[4][2]. Can anyone help? Thanks! Hi, I am inserting fields from a .csv file into database using integration engine(rhapsody) there is a javascript filter where I am trying to catch rows that have extra commas in the field text. Tried using the following code but the rows with extra commas just error and don't get inserted. Code: // Loop through all the input messages for (var i = 0; i < input.length; i++) { var next = output.append(input[i]); // Get the body of the current input message var body = input[i].text; // Set the body next.text = body; var name =next.getProperty("BaseFilename"); var fields = name; var fieldsList = fields.split(/\s*,\s*/); if (fieldsList.length >= 10) { name="error"+i; input.setProperty("BaseFilename", name ); } } ok im having a bit of problem with this. code : <input type="hidden" value="&nsbp;" name="b1r1c1"> (insde a table} <td></script>function ba1r1c1() { document.write(b1r1c1.value); }</script></td> (later on) <script> ba1r1c1(); </script> Whats happening is its not writing the space inside the cell but somewhere else on the page but i dont know why. The table is inside <div> tags if that helps. any help apreciated. Thanks I'm back, I think i've been up working on my service library too long ,,i'm confused on this subject of popup windows or something. Code: <html> <head> <script type="text/javascript"> function popUp(URL,Name) { var day = new Date(); var id = "page" + Name; window.open(URL, id, "toolbar=1,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=600,height=600"); var URL='https://www....com/'; } </script> </head> <body> <input type="text" <input type="button" onclick="javascript:popUp('Samsung_SB.asp?d=TRIAGE&SB='+'value')"> </body> </html> I'm lost where the text field comes into play..what i'm looking for is the following. input text in my case service bulletin doc number. which will then be appended to the end of the http addy after hitting enter and have the popup window open. I'm not gonna lie i have no clue as too what i'm doing Hello I would like to know how this is not functional. surely passing the function to another function would work so I can use the same variables without having to write it out again. [ICODE] <html> <head> <title>Number Conversions</title> <script> function addNumbers () { var firstnumber = document.calculator.myFirstNumber.value; var secondnumber = document.calculator.mySecondNumber.value; var total = parseInt(firstnumber) + parseInt(secondnumber); document.calculator.myTotal.value = total; document.calculator.myHex.value = total.toString(16); document.calculator.myOct.value = total.toString(8); document.calculator.myBinary.value = total.toString(2); document.write("End of Calculation."); } function subtractNumbers (addNumbers) { var total = parseInt(firstnumber) - parseInt(secondnumber); } </script> </head> <body> <form name="calculator"> First Number <input type=text name="myFirstNumber" value=0 size=3> <br> Second Number <input type=text name="mySecondNumber" value=0 size=3><br><br> <input type="button" value="ADD" onclick="addNumbers();"> <input type="button" value="SUBTRACT" onclick="subtractNumbers();"><br> Total <input type=text name="myTotal" value=0 size=3><br> Binary <input type=text name="myBinary" value=0 size=8><br> Octal <input type=text name="myOct" value=0 size=3><br> Hexidecimal <input type=text name="myHex" value=0 size=3><br> </form> </body> </html> [ICODE] |