JavaScript - Check Array
I have been banging my head on the wall with this one for a few hours. I mostly only program bash so this is a new world for me.
I am trying to have a script check a list of zip codes(preferably from a file) and if it is there it passes it to an order page and if not it goes to another URL. The basic idea is to check if you are within a service area before you can purchase a product. I have gotten nowhere fast with this so any help you can offer would be appreciated. Similar TutorialsHi guys. I'm working a bunch of pre existing code on a CMS. Just after a quick fix. Doing a show/hide thing on a particular div somewhere on the page depending if a checkbox is ticked or not. Currently there is 3 checkboxes that are dynamically added through the CMS. Here's simplified version of the form: Code: <form id="simplesearch" name="simplesearch"> <input type="checkbox" onclick='showhidefield(this.value)' name="meta_data_array_search_criteria[custom_profile_type][]" value="5" class="input-checkboxes" /> <input type="checkbox" onclick='showhidefield(this.value)' name="meta_data_array_search_criteria[custom_profile_type][]" value="4" class="input-checkboxes" /> </form> And here's the javascript I was playing with. Code: function showhidefield(id) { if(document.simplesearch.meta_data_array_search_criteria[custom_profile_type][''].checked) { document.getElementById("profile_fields_wrapper_" + id).style.visibility = "visible"; } else { document.getElementById("profile_fields_wrapper_" + id).style.visibility = "hidden"; } } Problem I'm having is how do i do a check to see if those checkboxes are checked in the javascript with those name arrays? How do i separate them? 'm guessing I have to loop through them or something?Hopefully that make senses - it's late here and I'm losing the plot Any pointers would be gratefully welcomed I am currently trying to check using javascript whether a php array contains a variable, and if it does then display a message. Any help would be much appreciated. I have written the following code... Code: <?php //php which sets users array to the results of the sql $selectquery = "SELECT Username FROM User"; $selectresult = mysql_query($selectquery); while ($row = mysql_fetch_array($selectresult)){ $users[] = $row['Username']; } ?> <script language="javascript" type="text/javascript"> function verifyUsername(array_var){ var user = document.getElementById("username").value; for(var i=0; i<array_var.length; i++){ if(array_var[i] == user){ document.getElementById("usernameerror").textContent = "already in array"; } } } </script> //html code for the form Username: <input type="text" name="username" id="username" onblur="return verifyUsername(<?php $users?>)"/> <span id="usernameerror" class="red"></span> Hiya, I'm looking for some guidance on a part of some coding practice I'm stuck on! I've created a shopping cart using javascript, the items save to the arrays etc and it all works fine. If the user adds the same product again to the cart the quantity is added onto the previous quantity that is already in the cart. To check if the item is already in the cart I've ued the below code, but what it does is update the quantity for the first cart, and when it updates the quantity for the second item it updates the quantity but keeps adding the same product to the cart in seperate elements of the array as well (if that makes sense? here are the two functions used: Code: function additem(id) { itemName = document.getElementById('name' + id).innerHTML; itemQuantity = parseInt(document.getElementById('quantity' + id).value); itemPrice = parseFloat(document.getElementById('price' + id).innerHTML); if(numitems == 0){ items[++numitems] = new Item(itemName,itemPrice,itemQuantity); displaycart(); } else{ checkarray(id, itemName, itemQuantity, itemPrice); } } function checkarray(id, itemName, itemQuantity, itemPrice){ for(i=1;i<=numitems;i++) { if(items[i].name == itemName){ items[i].quantity += parseInt(document.getElementById('quantity' + id).value); displaycart(); return true; } items[++numitems] = new Item(itemName,itemPrice,itemQuantity); } } It may jsut be a simple mistake I've made but it's been bugging me a lot and I can't seem to fix it, any help/pointers would be greatly appreciated. Hello I am trying to find a way to use the check all javascript code to select all my checkboxes within a while...loop. Codes goes as follows: within the header on the top of page 1: <SCRIPT LANGUAGE="JavaScript"> function CheckAll(chk) { for (i = 0; i < chk.length; i++) chk[i].checked = true ; } function UnCheckAll(chk) { for (i = 0; i < chk.length; i++) chk[i].checked = false ; } </script> The code that displays the checkboxes, which is a page included onto page 1: echo "<a class='comp' onclick='singleHideandShow({$row['pr_id']})' style='cursorointer'>{$row['propname']}</a><p>"; $propqry = mysql_query("SELECT * FROM users WHERE propid={$row['pr_id']}"); //using the hide and show id number, once clicked it will display the below contents echo "<div id={$row['pr_id']} style='display:none;'>"; while($propf = mysql_fetch_assoc($propqry)) { if($propf['uactive'] == "yes") { $pactive = "active"; } else { $pactive = "deactivated"; } //displays the information from the DB with a checkbox echo "<form name='myform' id='formmsg' method='post' action='profile.php?paction=edit&find=none' >"; echo " <input type='checkbox' name='check_list' value='{$propf['us_id']}'> <a href='profile.php?paction=edit&pid={$propf['us_id']}' /><img src='../images/secure/edit.png' name='Edit' border='0' /></a> <a href='profile.php?paction=delete&pid={$propf['us_id']}' /><img src='../images/secure/delete.png' name='Delete' border='0' /></a><label class='cuser'> {$propf['fname']} {$propf['lname']}, ({$propf['uname']}), {$pactive}</label><br>"; } echo "</form>"; echo '<p><input type="button" name="Check_All" value="Check All" onClick="CheckAll(document.myform.check_list)"> <input type="button" name="Un_CheckAll" value="Uncheck All" onClick="UnCheckAll(document.myform.check_list)"> <p>'; echo "</div>"; I receive the following error message when I click on the Check All button. Message: 'length' is null or not an object Line: 15 Char: 13 Code: 0 URI: http://www.domainname.com/profile.ph...edit&find=none Can anyone help me figure this out? On this webpage http://www.corkdiscos.com/testimonials.html i have a like button. when a user clicks like a comment box appears. when i unlike the button the comment box disappears this is ok but when a user has already liked the facebook page and comes to my webpage the comment box does not show. so im looking for a piece of javascript to check if a user has like the button on my page and if so to show the comment box. please check my source code of the website http://www.corkdiscos.com/testimonials.html to see what i have so far. any help would be greatly appreciated I am working on a page where the user will select a location from a dynamically generated dropdown list. I was able to create the php multidimensional array (tested and working) from a MySql database using the users information at login, but I'm having problems converting it to a javascript multidimensional array. I need to be able to access variables that I can pass to a number of text fields within an html form. For instance, if a user belongs to a company with multiple addresses, I need to be able to let them select the address they need to prepopulate specific text fields. php array creation: Code: if ($row_locations) { while ($row_locations = mysql_fetch_assoc($locations)) { $mail[$row_locations['comp_id']]=array('mailto'=>$row_locations['mailto'], 'madd'=>$row_locations['madd'], 'madd2'=>$row_locations['madd2'], 'mcity'=>$row_locations['mcity'], 'mstate'=>$row_locations['mstate'], 'mzip'=>$row_locations['mzip'], 'billto'=>$row_locations['billto'], 'badd'=>$row_locations['badd'], 'badd2'=>$row_locations['badd2'], 'bcity'=>$row_locations['bcity'], 'bstate'=>$row_locations['bstate'], 'bzip'=>$row_locations['bzip']); } } javascript function - this should create the array and send variables to text fields. Code: function updateAddress() { var mail = $.parseJSON(<?php print json_encode(json_encode($mail)); ?>); { if (comp_id in mail) { document.getElementById('mailto').value=mail.comp_id.mailto.value; document.getElementById('madd').value=mail.comp_id.madd.value; document.getElementById('madd2').value=mail.comp_id.madd2.value; document.getElementById('mcity').value=mail.comp_id.mcity.value; document.getElementById('mstate').value=mail.comp_id.mstate.value; document.getElementById('mzip').value=mail.comp_id.mzip.value; } else { document.getElementById('mailto').value=''; document.getElementById('madd').value=''; document.getElementById('madd2').value=''; document.getElementById('mcity').value=''; document.getElementById('mstate').value=''; document.getElementById('mzip').value=''; } } } Where is this breaking? Thanks in advance. I have the following array that contain the people who are on off on certain time: Code: var all = [ ["1234", "Jim", "2011-10-23 00:00:00", "2011-10-25 07:00:00"], ["1235", "Jack", "2011-10-21 00:00:00", "2011-10-21 08:00:00"], ["1236", "Jane", "2011-10-11 00:00:00", "2011-10-11 00:30:00"], ["1237", "June", "2011-10-20 00:00:00", "2011-10-20 12:00:00"], ["1238", "Jill", "2011-10-14 00:00:00", "2011-10-14 11:00:00"], ["1239", "John", "2011-10-16 00:00:00", "2011-10-16 10:30:00"], ["1240", "Jacab", "2011-10-19 00:00:00", "2011-10-20 08:30:00"] ]; The above array, I wish to use javascript to insert into the FullCalendar (http://arshaw.com/fullcalendar/). I notice that the only way seems to be using the FullCalendar array style (or structure) as follows: Code: $('#calendar').fullCalendar({ events: [ { title : 'event1', start : '2010-01-01' }, { title : 'event2', start : '2010-01-05', end : '2010-01-07' }, { title : 'event3', start : '2010-01-09 12:30:00', allDay : false // will make the time show } ] }); So, the question is: How do I insert my array to match with the FullCalendar array? cause FullCalendar array had a different array structure from my array - and I don't think so that I can write in this way: Code: $('#calendar').fullCalendar({ events:all }); Appreciate any help provided. I can't seem to figure out how to accomplish this. In my website, I would like the user to input text into a single or multiple textbox(es) and then have the contents of the textbox(es) stored to either a variable or an array. Then I would like to have that variable/array compared to other arrays. Basically, the user is searching for items in a database. The user can search for as many or as little items as they want. Then the item(s) will be compared to multiple arrays to find out if what the user wants is in the database. So for example, let's say the user is searching for recipes that have all or part of these ingredients: chicken, broccoli, lemon, honey. So, there would have been a total of 4 textboxes...one for each ingredient. These ingredients are stored to an array..lets call it ingredient(). In the database of recipes, each recipe has its own array which includes the ingredients needed to make the recipe, we'll call them tag1(), tag2(), and tag3(). Now, I want the array, ingredient(), to be compared to each of the "tag" arrays to see if any of the "tag" arrays include exactly match the ingredient() tag in part or in whole. Is this possible? Hey guys, I'm hoping this is possible or that there is an easier way to do this. I'm having an issue with displaying data from one array that contains information about users in a table that is controlled by a different array. Is it possible to do this or is this use of arrays to display the data the wrong approach? The table is located on one webpage, I simply want to extract one piece of information that I have placed in the initial array as part of the login script that contains user information (for validation for login etc) and display it in a table on the new webpage that is opened as a result of successful validation of the user details. I'm completely stumped and after many attempts I just can't seem to get it to work. Hi, Here is a working code to copy 2d php array to 2d javascript array. Code: <html> <head> <?php for($i = 0; $i < 3; $i++) { for($j = 0; $j < 2; $j++) {$quest[$i][$j] = $i*10+$j;} } ?> <script type="text/javascript"> var questions = new Array(3); for (var i = 0; i < 3; i++) { questions[i] = new Array(2); } questions[0] = ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"", $quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"", $quest[2]); ?>"]; document.write(questions[0][0] + "<br />"); document.write(questions[0][1] + "<br />"); document.write(questions[1][0] + "<br />"); document.write(questions[1][1] + "<br />"); document.write(questions[2][0] + "<br />"); document.write(questions[2][1] + "<br />"); </script> </head> </html> Now,here's the thing.Notice these lines in the code questions[0] = ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"", $quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"", $quest[2]); ?>"]; I would like to put these lines in a loop,something like for (var i = 0; i < 3; i++) { questions[i] = ["<?php echo join("\", \"", $quest[i]); ?>"]; } But even after a lot of efforts I am unable to do so,what am I doing wrong?Thanks Hi, i can't find the mistake in my little script hope someone can help me. PHP Code: <?php /* -------------------- read thumbfolder -------------------- */ function isRdyPfD($filename){ if ($filename == '.' || $filename == '..') { // To-Top-Dir return false; } $ext = explode(".",$filename); $ext = $ext[sizeof($ext) - 1]; $allowedformats = array ( 'jpg', 'png', 'jpeg', 'gif' ); return in_array($ext,$allowedformats); } function getPicsfromDir($dir){ /* array with names of the pictures in $dir */ if (is_dir($dir)) { if ($dh = opendir($dir)) { $filearray = array(); while (($file = readdir($dh)) !== false) { if (isRdyPfD($file) === true) { $filearray[] = $file; } } closedir($dh); return $filearray; } } else { return false; } } // End Function $thumbs = getPicsfromDir("./images/thumbs/"); /* -------------------- thumbfolder -------------------- */ echo "<div id='thumbslider'>\n"; echo "<ul id='thumbs'>\n"; for($i = 0; $i < count($thumbs); $i++){ echo "<li><img src=\"./images/thumbs/$thumbs[$i]\" onclick=\"thumbClick($i)\" /></li>\n"; } echo "</ul>\n"; echo "</div>\n"; /* -------------------- big size images folder -------------------- */ $bigSizeImages = getPicsfromDir("./images/"); //print_r($bigSizeImages); $jsValue = ''; for ($j=0; $j < count($bigSizeImages); $j++){ $jsValue = $jsValue . $bigSizeImages[$j]; if ($j < (count($bigSizeImages)-1)) { $jsValue = $jsValue . ","; } } ?> <script type="text/javascript"> images = new Array(<?php echo $jsValue ?>); function thumbClick(pos){ //alert(pos); alert(images[pos]); } </script> I can't trace the images array values? thanks for a feedback!!! Hi, In a nutshell,can anyone tell me how to copy a 2d (two dimensional ,2 dimensional) php array to 2d javascript array?I would be obliged if anyone can provide me a method of doing that OR I have written a code to copy a 2d php array to a 2d javascript array.It is working but there is one problem(please see the following).Can anyone tell me what I am doing wrong here? The 2d php array is $quest[100][6] and the 2d javascript array is questions[100][6] . I have written the javascript code inside the <?php....?> itself using echo "<script language="javascript" type="text/javascript">.......</script>; Now ,inside the javascript,when I try to copy the 2d php array to the 2d javascript array using the following method it works questions[0]= ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1]= ["<?php echo join("\", \"", $quest[1]); ?>"]; ... and so on However, if I try to do the same using the following method it does not work for (var i= 0; i <= 99; i++) { questions[i]= ["<?php echo join("\", \"", $quest[i]); ?>"]; } Why is that?What mistake am I making?Any help will be deeply appreciated.Thanks -----------------------------THE CODE------------------------------------ <?php Access database and store result of mysq_query in $result....... $result = mysql_query($query); for ( $count = 0; $count <= 99; $count++) { $quest[$count]=mysql_fetch_array($result,MYSQL_NUM);; } echo "<script language="javascript" type="text/javascript"> var questions = new Array(100); for (var i = 0; i <100; i++) { questions[i] = new Array(6); } /*The following method of copying 2d php array to 2d javascript array is not working for ( var i = 0; i <= 99; i++) { questions[i]= ["<?php echo join("\", \"", $quest[i]); ?>"]; } */ /*The following method ,however,is working*/ questions[0]= ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"",$quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"",$quest[2]); ?>"]; ....and so on </script>"; mysql_close($db_server); ?> this code is supposed to ask the users name and say how many letters in it get 2 random numbers ask user to add them if right say Well Done! if wrong say Sorry, you are wrong. when i run this nothing comes up whats wrong? thanx Code: <script> var firstName = ""; var numLetters = 0; firstName = prompt("Hi, what's your first name?", ""); numLetters = firstName.length; alert ("Did you know there are " + numLetters + " letters in your name?"); var num1 = Math.floor(Math.random()*9) + 1; var num2 = Math.floor(Math.random()*9) + 1; var answer; var useranswer; answer = num1+num2; useranswer = promt("What is" + num1 + "+" + num2 + "?"); If (answer = useranswer) { alert("Well done!"); } else { alert("Sorry, you are wrong."); } </script> I have a text input box that resets to blank when the user enters an alpha character, it also checks for the number 0 as it has to be greater than 0 too... when I submit the form it is blank the variable changes to blank (as I use parseInt to convert it to an integer at a later stage) What can I do to check and see if it is NaN value? (I've tried isNaN() and it did not do what I wanted it to) I'm having major pains trying to figure this out. I'm kind of new to Javascript, I need to open a text file from an external server, store each line in an array, then search that array for a certain word (HIGH), and if it exists then write something to the webpage, and if not, write something else. Here is what I have so far: Code: <html> <head> <title>Test</title> <script> <!-- function test(x) { if (wxd1txt.readyState === 4 && wxd1txt.status === 200) { // Makes sure the document is ready to parse and Makes sure it's found the file. var wxd1text = wxd1txt.responseText; var wxd1array = wxd1txt.responseText.split("\n"); // Will separate each line into an array var wxd1high = wxd1array.toString(); //Converting the String content to String //var highsearchreg = new RegExp("HIGH"); //var wxd1high = wxd1array[x].search(highsearchreg); document.write(wxd1high); if (wxd1high.search("HIGH") >= 0){ document.write("HIGH RISK");} else { document.write("NO RISK");} } } //--> </script> </head> <body> Hi! <script> <!-- var Today = new Date(); var ThisDay = Today.getDate(); var ThisMonth = Today.getMonth()+1; var ThisYear = Today.getYear(); var Hour = Today.getHours(); var Day2 = Today.getDate()+1; var Day3 = Today.getDate()+2; if (navigator.appName != "Microsoft Internet Explorer") { ThisYear = ThisYear + 1900;} if (ThisMonth < 10) { ThisMonth = "0" + ThisMonth;} if (ThisDay < 10) { ThisDay = "0" + ThisDay;} if (Hour == 2 || Hour == 22 || Hour == 23 || Hour == 0 || Hour == 1) { var wxHourd1 = 0600} else if (Hour >= 3 && Hour <= 10) { var wxHourd1 = 1300;} else if (Hour >= 11 && Hour <= 13) { var wxHourd1 = 1630;} else if (Hour >= 14 && Hour <= 16) { var wxHourd1 = 2000;} else if (Hour >= 17 && Hour <= 21) { var wxHourd1 = 0100;} //var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/"+ThisYear+"/KWNSPTSDY1_"+ThisYear+""+ThisMonth+""+ThisDay+""+wxHourd1+".txt"; var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/2010/KWNSPTSDY1_201005101300.txt" //(High risk day for testing) //document.write(wxurld1); //Use this to verify this section is working if (window.XMLHttpRequest) { wxd1txt=new XMLHttpRequest(); } else // IE 5/6 { wxd1txt=new ActiveXObject("Microsoft.XMLHTTP"); } wxd1txt.open("GET", wxurld1, true); wxd1txt.onreadystatechange = test(); // --> </script> </body> </html> When added to a webpage, nothing shows up except the "Hi!" and there are no errors in the Javascript Console in Google Chrome. Is this possible with Javascript, and if so, what am I doing wrong or not doing? Also, I have 2 URLs, one is a text file that has the HIGH text I want for an example, the other is the current file, which shouldn't have HIGH in it (unless the weather in the US turns really bad) Hi, I'm trying to create a test using Javascript. Actually, I did this in PHP, but we need to put it a server that does nor run it, I think I can convert it to Javascript. I hope it'll be work as in PHP somehow. Test will be composed of 15 questions and each question has either "Yes" or "No" as answer. And, I use radio buttons here for answers. By the way, there will be more than one radio groups. Now, I want to check the value of clicked radio button in each group and use an if-statement to determine if it's correct. And, if it's correct, I want to increment a variable by 1. Finally, by the resulted variable incremented for each question in the test, I want to use another if-statement to show specific result message for and interval of that variable. I tried this for one radio button like this: Code: <script language="JavaScript"> function get(form) { var ans1 = document.form.q1; var score = 0; for( i = 0; i < ans1.length; i++ ) { if( ans1[i].checked && ans1[i].value == no ) { score++; alert(score); } else {alert(score);} break; } } </script> <form name="form" method="get"> <input type="radio" name="q1" value="yes">Yes <input type="radio" name="q1" value="no">No* <input type="button" name="button" value="button" onclick="get(this.form)" /> </form> By the code above, it should alert 1 if "No" is checked and button is clicked and alert 0 if "Yes". This was a preliminary job for me to understand. And I couldn't do even this. Thank you. I got a page that gets created dynamically. sometimes I get images output with NO source like this Code: <img src="" id="md_1"> <img src="" id="md_2"> etc. etc. the image id are created dynamically also and always start with "0" and count up in order. I need to check everyone of those image links and when they are blank like above change the src to a default image. I have spent 8 hours on this one simple function and cannot seem to get it to work. I will call the function at the end of the page. This is perhaps a somewhat trivial point but it's bugged me a couple of times recently and I wondered if anyone out there had any thoughts on the matter. Essentially I have an action that can happen many times but I want to record whether it has happened at least once. I know we are talking about a trivial amount of processing and code here but is there any real difference between the following two methods: Code: myCheck: false, myRepeatedlyCalledFunction: function() { this.myCheck = true; // do some stuff } vs Code: myCheck: false, myRepeatedlyCalledFunction: function() { if(this.myCheck === false) { this.myCheck = true; } // do some stuff } thoughts? plz check bold part of function is not working. what is wrong with it.? Code: function onesizecheck(chk_id,siz) { alert(chk_id); if(document.getElementById('siz_check').value=='') { document.getElementById('siz_check').value=siz; }//end if if(document.getElementById('siz_check').value==siz) { document.getElementById('siz_check').value=siz; } else { alert('Multi size are not allowed.'); for(var i = 0; i < document.delet['checkbox[]'].length; i++){ var cb = document.getElementById('checkbox'); alert(cb[i].value); } } }//end function |