JavaScript - Match Function
Code:
function displayMessage(text) { // Open a new window var msgWindow = window.open('', 'Message'); // Write message in the new Window msgWindow.document.write(text); // Raise this window, in case it's not visible msgWindow.focus(); } //Enter total number of questions: var totalquestions=31 var mcquestions=13 var saquestions=18 var correctchoices=new Array("a","a","b","c","b","c","a","a","b","c","a","b","b"); var correctanswers=new Array("memory locations","_ underscore","x=5+5;","20","Else","lose win","ticker = ticker + 1;","Ticker = ticker + 1;","300.000","Jonathon \b","var","var counter;","var mark = 50, 70"); var shortanswers=new Array("identifier","assignment","false","true","false","reverse of the boolean result","the variable will be once the line is executed","var","value","2","4","2","3","no semi colon","no space/between else and if","missing curly bracket/no curly bracket","need else instead of else if"); function gradeit(){ var actualchoices=new Array() var msg1=new Array() var correctanswersno=0 var t=0 var sa=0 var displaycorrectanswers="" for (q=1;q<=mcquestions;q++){ var thequestion=eval("document.Questionform.q"+q) for (c=0;c<thequestion.length;c++){ if (thequestion[c].checked==true) actualchoices[q]=thequestion[c].value } if (actualchoices[q]==correctchoices[q]){ msg1[t]=q+")"+" Correct"; correctanswersno = correctanswersno + 1; t = t + 1; } else { msg1[t]=q+")"+" Incorrect: <br>Correct Answer: "+correctchoices[q]+") "+correctanswers[q]; t = t + 1; } } for (s=1;s<=saquestions;s++){ var saanswers=("document.Questionform.sa"+s).match(shortanswers[s-1]); if (saanswers.length==1){ sa = sa + 1; } } for (p=0;p<=12;p++){ displaycorrectanswers+="<br>"+msg1[p]; } var msg ="Multiple Choice Mark: "+correctanswersno+"/"+mcquestions+" <br><br>Individual Marks: "+displaycorrectanswers+"<br>Short answer Mark"+sa; displayMessage(msg); } Code: for (s=1;s<=saquestions;s++){ var saanswers=("document.Questionform.sa"+s).match(shortanswers[s-1]); if (saanswers.length==1){ sa = sa + 1; } } Every loop it looks through an individual textbox and if a word matches the word in the array, shortanswers, then this word is put into another array called saanswers and if this array has length 1 e.g. a word has been matched then 1 is added to sa. However it doesnt seem to work. any ideas? Similar TutorialsI have one (1) XML file that is used to display job announcement data in two ways: 1. an RSS feed 2. an HTML file using javascript. The RSS feed displays everything and that is good. But for the HTML file I only want some of the data to display not all of it. For instance, I want to display the announcements from the xml file ONLY where <grade> (<grade>FS-0203-7</grade>) starts with the letters "FS". I have tried this IF STATEMENT: if (("grade").match(/FS.*/)); but it does not work. How do I use Match so that it only writes grades from the XML file that start with "FS" or is there a better way to do this? Code: <script> . . . var x=xmlDoc.getElementsByTagName("item"); for (i=0;i<x.length;i++) { . . . document.write(x[i].getElementsByTagName("grade")[0].childNodes[0].nodeValue); document.write("</td><td>"); . . . </script> Code: function displayMessage(text) { // Open a new window var msgWindow = window.open('', 'Message'); // Write message in the new Window msgWindow.document.write(text); // Raise this window, in case it's not visible msgWindow.focus(); } //Enter total number of questions: var totalquestions=30 var mcquestions=13 var saquestions=18 var correctchoices=new Array("a","a","b","c","b","c","a","a","b","c","a","b","b"); var correctanswers=new Array("memory locations","_ underscore","x=5+5;","20","Else","lose win","ticker = ticker + 1;","Ticker = ticker + 1;","300.000","Jonathon \b","var","var counter;","var mark = 50, 70"); var shortanswers=new Array(/identifier/gi,/assignment/i,/false/i,/true/i,/false/i,/reverse of the boolean result/i,/the variable will be once the line is executed/i,/var/i,/value/i,/2/i,/4/i,/2/i,/3/i,/no semi colon/i,/no spacebetween else and if/i,/missing curly bracket/i,/need else instead of else if/i); function gradeit(){ var actualchoices=new Array() var msg1=new Array() var msg2=new Array() var correctanswersno=0 var t=0 var f=0 var sa=0 var foundMatches = 0; var displaymcanswers="" var displaysaanswers="" //Works out mark for Short-answer Questions// for (s=1;s<saquestions;s++){ var saanswers = [] if ((saanswers.push(((document.Questionform["sa" + s]).value).match(shortanswers[s-1]))) == 1 ) { msg2[f]=s+")"+" Correct"; sa++; } else { msg2[f]=s+")"+" Incorrect: <br>Correct answer should include the word: "+shortanswers[s-1]; } f = f + 1; } This piece of code marks answers from a user which they have entered into textboxes. So for each answer the code uses the match function to see if it matches a specific pattern. However, at the moment the code says all the user answers are correct when are answers are actually wrong. Ideas? eg: there is a url as this: http://example.com i want to make a match that the second part in the url are beginning of test. eg: Code: http://example.com/test/... thank you. ;(function($){ $.fn.superfish = function(op){ In the above code snippet: Firstly I find it odd the the line begins with a ';'. Is there a meaning to this? Secondly, what is the meaning of the '$' in this context and why does it appear that there is a parenthesis missing? I am good with C# and now I am learning JavaScript Thanks for the help out, joecamel This functions should replace uppercase chars with bold and lowercase with italic. It should return: Big Bad wolf, Small red ball - HI Unfortunately there's something wrong with it and I'm getting this: Big Bad wolf, Small red ball - HI Not sure what 's wrong. Code: function replaceIt(mystr){ var str = "Big Bad wolf, Small red ball - HI"; var tmppicstr = ""; var tregex = /[^a-zA-Z\s-,\/]/; var lccheck = /[:lower:]/; var ltcheck = /[a-z]/i; if(tregex.test(str) == true){ return str; } else { for(var x=0;x<=str.length;x++){ var tmpchar = str.substring(x, (x+1)); if(ltcheck.test(tmpchar) == true){ if(lccheck.test(tmpchar) != true){ tmppicstr = tmppicstr + "<b>" + tmpchar + "</b>"; }else{ tmppicstr = tmppicstr + "<i>" + tmpchar + "</i>"; } } if(tmpchar == " ") tmppicstr = tmppicstr + (" "); if(tmpchar == ",") tmppicstr = tmppicstr + ("<b>" + tmpchar + "</b>"); if(tmpchar == "-") tmppicstr = tmppicstr + ("<i>" + tmpchar + "</i>"); if(tmpchar == "/") tmppicstr = tmppicstr + ("<b class='sl'>" + tmpchar + "</b>""); } } return tmppicstr; } Hi, I am using the following code to generate a temporary window: In the js: Code: var win=null; function NewWindow(mypage,myname,scroll){ settings='width=850,height=500,top=200,left=50,scrollbars=yes,location=yes,directories=no,status=no,menubar=no,toolbar=no,resizable=yes'; win=window.open(mypage,myname,settings); if(win.focus){win.focus();}} function hidestatus(){ window.status='' return true } And in the HTML: Code: <a href=\"http://www.support-focus.com/check.php?key=$sup_cd2\" onclick=\"NewWindow(this.href,'','yes','default'); return false\" onfocus=\"this.blur()\" > This code works , but I don't understand the mis-match or parameters This is passing four param: onclick=\"NewWindow(this.href,'','yes','default'); But this is only receiving three: NewWindow(mypage,myname,scroll) Is the last one (default) not counted for some reason ? The was able to move the scroll param (yes) out With this: onclick=\"NewWindow(this.href,'','default'); and NewWindow(mypage,myname) Which now leaves just two params and a default. Does anyone know why this appears to be unbalanced and also what the myname param does? ( do I need it ? can I get rid of the '' and the myname ? ) Thanks hey guys i have the following test html that i want to grab information out of in paticular .match(/\s(\d{1,2}\%)<\/td>/)[1]; now this works for the first % which returns 4% on this line <td style="color: white;"> (4%)</td> but then i have the same matches again Code: CL = temp.match(/\s(\d{1,2}\%)<\/td>/)[1]; alert("CL = " + CL); //returns 4% Neo = temp.match(/\s(\d{1,2}\%)<\/td>/)[2]; alert("Neo = " + Neo);//returns undefined and should return 2% Oak = temp.match(/\s(\d{1,2}\%)<\/td>/)[3]; alert("Oak = " + Oak); //returns undefined and should return 14% Queen = temp.match(/\s(\d{1,2}\%)<\/td>/)[4]; alert("Queen = " + Queen); // returns undefined and should return 27% here is a link to the temp variable because it would get messy here http://pastebin.com/XFyiQ26K I still working on this script for sorting fields in a wiki and have ran into another feature I'm trying to get working. Right now I have a long list that needs to be sorted and it looks like this: [[wiki:softwa softwarename|Display Text]] [[wiki:somethingelse:alphaname|Alpha Text]] [[wiki:whoops:etchers|Elephants]] The first part of my code is an attempt to match those with a regular expression: Code: else if (text.match(/\[\[(.*):(.*)\]\]/)) { return sorttable.sort_link; } The second part is the actual sorting: Code: sort_link: function(a,b) { aa = a[0].split(":",4); bb = b[0].split(":",4); if (aa[3]==bb[3]) {return 0;} if (aa[3]<bb[3]) {return -1;} return 1; }, I'm pretty sure the regular expression works... at least it works on some regular expression "testings" websites. But I just cant get these links to sort. I am trying to wort by the Display text which is located after the '|' in the text. Hi, I have the following code: Code: var str = "/dev/filler/test0/"; var patt = new RegExp("/ test0 /$"); var result = patt.exec(str); document.write(result); which returns: /test0/ in the var patt line I would like to replace the hardcoded test0 string with an expression that matches any characters between the two forward slashes. I have tried with little success. Why do I get both the greedy and non-greedy? How do I extract "somestring" only? I'm on IE7. thanks Code: <script type="text/javascript"> var x = "(EVAL)(H:somestring)Some other Text here"; var full =(x.match(/\(H\:(.*?)\)/g)); // produces "(H:somestring)" as expected alert(full); var inside = (x.match(/\(H\:(.*)\)/)); // produces "(H:somestring),somestring" .. I only want "somestring" alert(inside); </script> I am trying to do a pattern match and check something in a condition but cant get it to work. The first value changes and I need to check and do something if I get a hit on it. Code: var mydata = "?first=one&second=two&third=three"; if (mydata.indexOf("first") == "something") { alert("No Hit"); } else { alert("Hit"); } Basically I am trying to find out if first is equal to one in the mydata string. Please advise because my above attempt is not working. Hello All, Below is my code, I am needing to get to where the label name will match the behavior that my field currently does. If nothing is entered the field is changed to a red background. If it is focused it goes back to white. I am needing the font color of the label to match color of the field and match the same behavior. 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>Lab06 - Form Validation</title> <script type="text/javascript" charset="utf-8"> function passcheck(){ var pw1 = document.forms[ 0 ].password.value; var pw2 = document.forms[ 0 ].passcomf.value; if ( pw1 != pw2 ) { alert ("You did not enter the same new password twice. Please re-enter your password."); return false; }else{ return true; } } function validate( ) { var errors = new Array( ); for( var i = 0; i < document.forms[ 0 ].elements.length ; i++ ){ if( document.forms[ 0 ].elements[ i ].type == "text" ) { if( document.forms[ 0 ].elements[ i ].value == "" ){ errors.push( "The " + document.forms[ 0 ].elements[ i ].name + " field cannot be blank.\n"); document.forms[ 0 ].elements[ i ].className = "in_error"; } } if( document.forms[ 0 ].elements[ i ].type == "select-one") { if(document.forms[ 0 ].elements[ i ].selectedIndex == 0 ) { errors.push( "The " + document.forms[ 0 ].elements[ i ].name + ' was not "Yes, I agree!", you must agree to the "User Agreement."\n'); document.forms[ 0 ].elements[ i ].className = "in_error"; } } if( document.forms[ 0 ].elements[ i ].type == "select-one") { if(document.forms[ 0 ].elements[ i ].selectedIndex == 2 ) { errors.push( "The " + document.forms[ 0 ].elements[ i ].name + ' was not "Yes, I agree!", you must agree to the "User Agreement."\n'); document.forms[ 0 ].elements[ i ].className = "in_error"; } } } if( errors.length == 0 ) { return true; } else { clear_errors( ); show_errors( errors ); return false; } } function clear_errors( ){ var div = document.getElementById( "errors" ); while( div.hasChildNodes( ) ){ div.removeChild( div.firstChild ); } } function show_errors ( errors ) { var div = document.getElementById( "errors" ); for( var i = 0; i < errors.length; i++ ){ var error = document.createTextNode( errors[ i ] ); var p = document.createElement( "p" ); p.appendChild( error ); div.appendChild( p ); } } window.onload = function( ) { document.forms[ 0 ].onsubmit = validate; } </script> <style type="text/css" media="screen"> #errors { color: #F00; } .in_error { background-color: #F00; } input:focus { background-color: #FFF; } select:focus { background-color: #FFF; } </style> </head> <body> <h1>Form Validation</h1> <div id="errors"></div> <form action="" method="post" onsubmit="return passcheck()"> <p> <label for="firstname" id="labelfirstname">First name:</label> <input type="text" name="First name" value="" id="firstname" /> </p> <p> <label for="lastname" id="labellastname">Last name:</label> <input type="text" name="Last name" value="" id="lastname"/> </p> <p> <label for="middlei" id="labelmiddlei">Middle initial:</label> <input type="text" name="Middle initial" value="" id="middlei"/> </p> <p> <label for="address" id="labeladdress">Street address:</label> <input type="text" name="Street address" value="" id="address"/> </p> <p> <label for="city" id="labelcity">City:</label> <input type="text" name="City" value="" id="city"/> </p> <p> <label for="State" id="labelstate">State:</label> <input type="text" name="State" value="" id="state"/> </p> <p> <label for="zipcode" id="idzipcode">Zipcode:</label> <input type="text" name="Zipcode" value="" id="zipcode"/> </p> <p> <label for="username" id="labelusername">Username:</label> <input type="text" name="Username" value="" id="username"/> </p> <p> <label for="password" id="labelpassword">Password:</label> <input type="text" name="Password" value="" id="password"/> </p> <p> <label for="passcomf" id="labelpasscomf">Password comfirmation:</label> <input type="text" name="Password comfirmation" value="" id="passcomf"/> </p> <p> <label for="agreement" id="labelagreement">User Agreement</label> <select name="User Agreement" id="agreement"> <option></option> <option>Yes, I agree!</option> <option>No, I do not agree!</option> </select> </p> <p><input type="submit" value="Register →" onclick="return passcheck(); return true;"/></p> </form> </body> </html> Hi, I found this regular expression on the internet and it works fine when I test it in various validators on the web. Code: ^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$ It's purpose is to validate dates entered as mm/dd/yyyy, m/dd/yyyy, mm/d/yyyy or m/d/yyyy. When I try it with the code below it always returns null. Code: function isValidDate(/* String */ p1_date) { var x = "^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$"; var re = new RegExp(x); var myValid = p1_date.match(re); alert("p1_date: " + p1_date + "\nmyValid: " + myValid); return myValid; } Suggestions? Hello, I am trying to parse a string using regular expressions. This string can potentially have any number of non-alphanumeric characters acting as delimiters. These delimiters can also be grouped together. Here are some examples of the data: 00923:5342:123 --> I want to extract 00923, 5342 and 123 into an array 08765::764375 --> parse this as 08765 and 764375 into an array 3246//672354//23458 --> parse as 3246, 672354 and 23458 23564-73654 --> etc I'm using the following code: Code: var ids = str.match(/\w*/g); But it just returns the first token from each line and ignores the rest. So with the above data I'm only getting back 00923, 08765, 3246 and 23564 into the first element of the "ids" array. I've also tried an "inverse" approach using the split method like so: Code: var ids = str.split(/\W*/g); and I just get the same result - the first token from each line is only returned. My test code looks like this ('str' contains a string read in from a file): Code: var ids = str.match(/\w*/g); //var ids = str.split(/\W*/g); task.logmsg("the length of the array is " + ids.length); for (i = 0; i < ids.length; i++) { task.logmsg("ids=[" + i + "]=" + ids[i]); } I can confirm that ids.length is returning 1 (??) The 'task' object comes from a separate library and the 'logmsg' method just writes to the console. My reptilian brain is struggling with reg exps. This shouldn't be difficult to do, but I just can't get it to work. If anyone out there can lend some assistance, it would be greatly appreciated. Thanks, JD I'm building a shop and would like to have some sort of mix and match functionality where the visitor can match tops and bottoms. Anybody have any ideas as to how I would maybe build something like this? Is there a plugin already out there for something similar to this by any chance? I guess something like Abercrombie's site but instead I'd have two rows: one for the tops and one for the bottoms. 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> 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 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 |