JavaScript - Exec Method Issue
Hi guys
For learning (regx), I'm working with the following example taken from an old resource. Example 1 is the original code and example 2 is my effort because I couldn't get example 1 to work. Any idea why example 1 doesn't work? Is the shortcut notation not valid anymore? LT Code: Example 1. In the following example, RegExp.input is set by the Change event. In the getInfo function, the exec method, called using the () shortcut notation, uses the value of RegExp.input as its argument. <script type="text/javascript"> function getInfo(){ //example 1 //doesn't work. a = /(\w+)\s(\d+)/(); alert(a[1] + ", your age is " + a[2]); } function getInfo2(info){ //example 2. works. //alert(info); re = /(\w+)\s(\d+)/; mArry = re.exec(info); alert(mArry[1] + ", your age is " + mArry[2]); } </script> </head> <body> <form> <!-- example 1 original //--> <input type="text" name="NameAge" onchange="getInfo(this);" /> <!-- example 2 //--> <input type="text" name="NameAge" onchange="getInfo2(this.value);" /> </form> Similar TutorialsHi, I have form with with few inputs, form some reason hitting "Enter" on input field does not submit the form in IE. But it works in FF. so i did the following code to do the form submit. But i want to call the form 'onSubmit()' instead of submitting it. bcos i do some validation there. IE keeps saying 'form.onSubmit()' object is undefined. How to call this method? if (e.nativeEvent.keyCode == 13) { var form = document.getELementById(formId); form.submit(); return false; } thanks bk Why is the callwhy is the slice method only a method of an Array instance? The reason why I ask is because if you want to use it for the arguments property of function object, or a string, or an object, or a number instance, you are forced to use Array.prototype.slice.call(). And by doing that, you can pass in any type of object instance (Array, Number, String, Object) into it. So why not just default it as a method of all object instances built into the language? In other words, instead of doing this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; console.log(typeof arguments);//Object console.log(arguments instanceof Array);//false var args1 = Array.prototype.slice.call(arguments); console.log(args1); var args2 = Array.prototype.slice.call(obj); console.log(args2); var args3 = Array.prototype.slice.call(num); console.log(args3); var args4 = Array.prototype.slice.call(string); console.log(args4); Core('dom','event','ajax'); Why not just be able to do this: Code: function Core(){ var obj = {a : 'a', b : 'b'}; var num = 1; var string = 'aff'; var args = arguments.slice(0); var args2 = obj.slice(0); var args3 = num.slice(0); var args4 = string.slice(0); //right now none of the above would work but it's more convenient than using the call alternative. } Core('dom','event','ajax'); Why did the designers of the javascript scripting language make this decision? Thanks for response. When you use a form and submit it the URL bar changes to what the submitted values are. So can anyone explain how to use this?
I'm trying to write a method called printPowersOfN that accepts a base and an exponent as arguments and prints each power of the base from base0(1) up to that maximum power, inclusive. For example, I'm trying: printPowersOfN(4, 3); printPowersOfN(5, 6); printPowersOfN(-2, 8); which should give me: 1 4 16 64 1 5 25 125 625 3125 15625 1 -2 4 -8 16 32 64 -128 256 but I only get: 64 15625 256 Here's my code: Code: public class Powers { public static int printPowersOfN (int base, int exponent) { int answer = 1; for (int i=1; i <= exponent; i++) { answer*=base; } return answer; } public static void main(String[] args) { System.out.println(printPowersOfN(4, 3)); System.out.println(printPowersOfN(5, 6)); System.out.println(printPowersOfN(-2, 8)); } } What should I change so that it does all of the powers? I am using javascript for adding and removing rows from table as per user require ment like if we press ADDROW button it adds extra row to table and if we pressREMOVEROW it delets the last row.. Now i want to access the data from textbox like this.. var crpt = document.getElementById("itrtr2").value; //no. of rows for(var k=1;k<=crpt;k++) { qtyc = document.getElementById("txtRowc3"+k).value; unit_pricec = document.getElementById("txtRowc5"+k).value; alert('QTYC:'+qtyc+' UPC:'+unit_pricec); cttl = qtyc * unit_pricec; document.getElementById("txtRowc6"+k).value = cttl.toFixed(2); csbttl = csbttl + cttl; } document.getElementById("subttlC").value=csbttl.toFixed(2); it shows the value of textRowc3i in qtyc in alert box but also givs error document.getElementById("txtRowc3"+k) is null.. I tried for this but problem is not solved please help... Thank You... i want to write a code which would prompt the user for his first name and last name with space in between them.The full name must be entered in the same prompt box.Using the charCodeAt() method i wanna test the first character of the user's first name as well as last name.If the first character of first name is in lowercase then it should alert the user as "first name must start with uppercase".And if the first character of second name is in uppercase then it should alert the user as "second name must start with lowercase". ..plzzzz help me and give me some code for this..i m a beginner in javascript..
Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm Code: window.onload = initForm; function initForm() { document.getElementById("months").selectedIndex = 0; document.getElementById("months").onchange = populateDays; } function populateDays() { var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31); var monthStr = this.options[this.selectedIndex].value; if (monthStr != "") { var theMonth = parseInt(monthStr); document.getElementById("days").options.length = 0; for(var i=0; i<monthDays[theMonth]; i++) { document.getElementById("days").options[i] = new Option(i+1); } } } Thank you! I am very interested in learning this and would love any help! So I'm new around here, and to web dev in general, but I've got a (hopefully) short question. I am trying to call a function (nextMonth()) every second from the time that the cycle method gets called, until it is called again. As of now I am trying to use setInterval, (and I previously tried with setTimeout and using a callback argument but maybe I wasn't doing that properly). The problem is that after running the cycle() method for 5 or 6 seconds, the entire browser freezes up and you have to kill it and restart it. Here is my code as of now: Code: function cycle() { if(CYCLEINT != null) //STOP THE CYCLE LOOP { window.clearInterval(CYCLEINT); CYCLEINT = null; document.getElementById("cycle").innerHTML = "Cycle Months"; } else //LOOP IS NOT RUNNING, INITIATE AND CONTINUE INTERVAL. { CYCLEINT = self.setInterval("nextMonth()", 1000); document.getElementById("cycle").innerHTML = "Pause"; } } function prevMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal > 1) { dVal--; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } } function nextMonth() { var dVal = $( ".slider" ).slider( "option", "value"); if(dVal < dateMax) { dVal++; $( ".slider" ).slider( "option", "value", dVal ); refresh(); } if(CYCLEINT != null && dVal >= dateMax) { cycle(); } } Hi there I'm trying to figure out what the following syntax for split means in the following line of the code arrTest[0].split('/')[0] what does ('/')[0] means in split('/')[0]? please can anyone explain Write a public static method named starPrinter that will take an int as a parameter and print lines of stars as shown below. The header of the method will be public static void starPrinter(int n) . This is what it should look like: Please help! Sup gents. Im having problems with the link method. Its tied up to a button in the form. The link method sees the "global" variable and determines if its 1 or 0. If its 1 it gives a certain msg and if its 0 another one. Problem its always reading the variable as 0 and giving me the same message regardless of the fact that im typing the username and password correc Code: <html> <head> <script type ="text/JavaScript"> var counter = 0; var counter2 = 0; var arraynumb = 0; var arraynumb2 = 0; var global; var array = ['Mohamad', 'Karim', 'Anthony', 'Rami', 'Natalia', 'Sarah', 'Samer', 'Violette', 'Plume', 'Sharshabil']; var array2 = ["1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009"]; function pass(){ var searchKey = document.searchform.inputVal.value; for (var i = 0, len = array.length; i < len; i++){ if (array[i] == searchKey){ counter = 1; arraynumb = i; } } } function pass1(){ var searchKey2 = document.searchform.inputVal2.value; for (var i = 0, len = array2.length; i < len; i++){ if (array2[i] == searchKey2){ counter2 = 1; arraynumb2 = i; } } } function access(global) { if (counter == 1 && counter2 == 1 && arraynumb == arraynumb2) { window.alert("You may now access the website"); global = 1; } else window.alert("You may not access the website"); global = 0; } function link(global) { if (global == 1) { window.alert("you may proceed to the link"); } else window.alert("you are not signed in, please do so"); } </script> </head> <body> <form name = "searchform" action = ""> <p>Enter username<br/> <input name = "inputVal" type = "text" size = "30"/> <input name = "search2" type = "button" value = "Search" onclick = "pass()"/> </p> <p>Enter password<br/> <input name = "inputVal2" type = "password" size = "30"/> <input name = "search" type = "button" value = "Search" onclick = "pass1()"/> <input name = "Access site" type = "button" value = "Access" onclick = "access()"/> <input name = "link to" type = "button" value = "link" onclick = "link()"/> <br/> </p> <br/> <p></p> </form> </body> </html> I am trying to impliment Javascript code to replace the MS Tabular data control. How do I go about creating a Fields collection object that has a default method of Item(idx) ie. myrs.Fields.Item(4).name is the same as myrs.Fields(4).name I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. Have the code check that the statement has at least one character. You can do this by using the trim method to remove spaces from the beginning and end, and then checking the length of the trimmed string. If there are no characters, the response should tell the user to enter something. For example, a possible statement and response would be: Statement: Response: Say something, please. Could someone help me with this? I'm not sure how to make it check to see if the user input has 0 characters. would it be better to place the javascript into a .js file or just place the js code somewhere else in the html? How should it look? Code: <div style="width: 225px; height: 155px; float: left; height: 16px; background-color: #000000; color: #FFFFFF; margin-left: 0px; margin-bottom: 0px; font-size: small; padding-left: 0px;"> <img alt="" src="images/news.png" height="16" width="222" /><div style="width: 225px; height: 155px; float: left;"><script type="text/javascript">// <![CDATA[if(document.layers){document.write('<ilayer id="ns4div" width="'+swidth+'" height="'+sheight+'" bgcolor='+sbcolor+'><div id="ns4div1" width="'+swidth+'" height="'+sheight+'" onmouseover="sspeed=0;" onmouseout="sspeed=rspeed"></div></ilayer>')} if(document.getElementById||document.all){document.write('<div style="position:relative;overflow:hidden;width:'+swidth+'px;height:'+sheight+'px;clip:rect(0 '+swidth+'px '+sheight+'px 0);background-color:'+sbcolor+';" onmouseover="sspeed=0" onmouseout="sspeed=rspeed"><div id="iens6div" style="position:relative;width:'+swidth+'px;"></div></div>');} // ]]></script> </div></div> If anyone could help me, I would soooo appreciate it. I'm writing this program and I can't seem to figure out what the problems is. I'm new to this and really bad at it. public class Points { int ycoordinate; int xcoordinate; public Points(){ ycoordinate=0; xcoordinate=0; } public Points(int xcoord, int ycoord) { xcoordinate=xcoord; ycoordinate=ycoord; } public int getxcoordinate() { return xcoordinate; } public int getycoordinate() { return ycoordinate; } public void setxcoordinate(int xcoord) { xcoord=xcoordinate; } public void setycoordinate(int ycoord) { ycoord=ycoordinate; } public int distanceFromOrigin() { int point1=(xcoord-0)*(xcoord-0); int point2=(ycoord-0)*(ycoord-0); int distance=Math.sqrt(point1+point2); } public String Points() { String str="The distance between the coordinates is:"+""+distance; return str; } } I don't even know where to begin with this one. I don't know the terminology for what I am trying to do here, and the sample code is too big and cluttered to post. So I put together the following to illustrate the structure of the object that I am trying to overcome. I have a method chain within an object, and I need to override one of the methods, but when I do so I loose access to the private methods and properties of it's containing object... I googled this for several hours, and the best that I can come up with is that I need to somehow use call() to access the scope of another object. But I don't understand call() or apply() at all, and I've read many tutorials on those... Code: window.oModule['Report'] = (function(){ var _privateProp1 = '' , _privateMethod1 = function(){ // ... } , _publicMethod1 = function(){ // ... } , _publicMethod2 = (function(){ var _sub_privateProp1 = '' , _sub_privateMethod1 = function(param1,param2){ // ... } , _sub_publicMethod1 = function(){ // ... } , _sub_publicMethod2 = function(start , end){ // I need to replace this method from somewhere else var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... _neededValue += _sub_privateMethod1(arg1,arg2) } return _neededValue; } ; return{ '_sub_publicMethod1' : _sub_publicMethod1 , '_sub_publicMethod2' : _sub_publicMethod2 } })() ; return{ '_publicMethod1' : _publicMethod1 , '_publicMethod2' : _publicMethod2 } })(); alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This works fine oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; // ... return start+end } alert(oModule.Report._publicMethod2._sub_publicMethod2(1,5)) // This will alert 6 (as intended) oModule.Report._publicMethod2._sub_publicMethod2 = function(start,end){ // Doing this modifies the output of all expressions that already call the sub method (which is what I need) var _neededValue = ''; for(var i = start ; i<end ; ++i) { // ... different set of instructions _neededValue += _sub_privateMethod1(arg1,arg2) // This line causes an error: _sub_privateMethod1 is undefined } return _neededValue } Hello, I was able to solve an issue I had in previous post in writing some code to grab a section of a cookie value string (2 letter state ex MD) and check against it to do something. That was easy because the state was at the end of the string and all I had to do was use the slice() method. Now I was to be able to grab the 2 letter state from a string that looks like this: BALTIMORE, MD|blah blah|blah blah|blah blah (the real cookie value string will always be separated with pipes (|)) Can anyone please help? Thanks in advance! Code: <HTML> <HEAD> <TITLE></TITLE> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <SCRIPT LANUAGE="JavaScript"> function setCookie(name, value, expires, path, domain, secure) { document.cookie= name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : ""); } function getCookie(name) { var dc = document.cookie; var prefix = name + "="; var begin = dc.indexOf("; " + prefix); if (begin == -1) { begin = dc.indexOf(prefix); if (begin != 0) return null; } else { begin += 2; } var end = document.cookie.indexOf(";", begin); if (end == -1) { end = dc.length; } return unescape(dc.substring(begin + prefix.length, end)); } </SCRIPT> </HEAD> <BODY> <script> $(function(){ $('div').each(function(){ if($(this).hasClass('stateSelect1')){ if (getCookie("location")!=null){ var state = getCookie("location").slice(-2).toLowerCase(); var stateArray = []; stateArray = $(this).attr('rel').toLowerCase().split(','); if($.inArray(state,stateArray) >= 0){ $(document).ready(function(){ $(".stateSelect0").css("display","none"); $(".stateSelect1").css("display","block"); }); } } } }); }); </script> <strong>Step 1. Copy and paste in cookie set text field:</strong> <br> <br> <strong>Show Image1:</strong><br> CHARLOTTE, NC|blah blah|blah blah|blah blah|blah blah<br> BALTIMORE, MD|blah blah|blah blah|blah blah<br> <br> <strong>Show Image2:</strong><br> COLUMBIA, SC|blah blah|blah blah|blah blah<br> RESTON, VA|blah blah|blah blah|blah blah<br> <br> <strong>Show Image3:</strong><br> LOS ANGELES, CA|blah blah|blah blah|blah blah<br> SEATLE, WA|blah blah|blah blah|blah blah<br> <br> <br> <strong>Step 2.</strong> <input type="button" value="Set Cookie" onclick='setCookie("location", prompt("Enter your location"))' /> <br> <br> <strong>Step 3.</strong> Now refresh page. <br> <br> <style> .default{ border:3px solid limegreen; margin-bottom:5px; width:200px} .div1{ border:3px solid red; margin-bottom:5px; width:200px} .div2 { border:3px solid purple; margin-bottom:5px; width:200px} .div3 { border:3px solid yellow; margin-bottom:5px; width:200px} .div4 { border:3px solid blue; margin-bottom:5px; width:200px} </style> <!--DEFAULT IMAGE IF NO COOKIE SET OR NON LISTED STATE--> <div class="stateSelect0 default"> DEFAULT IMAGE </div> <!--DEFAULT IMAGE IF NO COOKIE SET OR NON LISTED STATE--> <div class="stateSelect1 div1" rel="NC,MD" style="display:none">Image 1 - DIV 1</div> <div class="stateSelect2 div2" rel="SC,VA" style="display:none">Image 2 - DIV 2</div> <div class="stateSelect3 div3" rel="WA,CA" style="display:none">Image 3 - DIV 3</div> </BODY> </HTML> I am using this method inside a if and whenever controller come to this point it is throwing an undefined exception intead it should check if null or anything present. How to handle this?
|