JavaScript - Check If Array Contains Variable
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> 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 Dear all, The code below puts a link in mydiv when the page loads if myvar equals 1. Great till here, but if myvar changes its value and it does not equal 1 any more I have to reload the page in order not to see the link. What do I have to do to avoid that reload? what do I have to do to check myvar's value for changes constantly? Thanks in advance! Code: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script> <script> var myvar=1; function func1() { if (myvar==1){ var putit=""; putit +="<a href='#'>Put this link</a>"; $("#mydiv").html(putit); } } function addLoadEvent(func) { $(window).load(func); } addLoadEvent(func1); </script> </head> <body> <div id="mydiv"></div> 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. I am very new to coding, trying to teach myself some javascript. I know this is a very simple code, I just can't seem to nail down what is going wrong. Feeling really stupid right now. Heres the code: Code: <html> <head> <script language="JavaScript"> var choice=confirm("Press ok for black. Press cancel for red."); if (choice==true){ document.bgColor="yellow"; document.fgColor="black"; } else { document.bgColor="red"; document.fgColor="white"; } </script> <body> <p>words</p> </body> </html> If someone could take a second to set me straight, I would really appreciate it. btw: hope I posted all this according to the "rules". I tried 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? 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. If I assign an array to another variable, any changes to the array change both variables. Is it a pointer instead of a copy? Try this: Code: <script type="text/javascript"> Arr=['a','b','c']; Arr2=Arr; Arr[1]='_'; alert('Array 1: '+Arr); alert('Array 2: '+Arr2); // Both arrays become 'a','_','c' </script> Why's this happen? Is it to be expected? Variables don't do this but it's happening for arrays in IE and FireFox, maybe all others. I was wondering if it is possible to put all the non null variables of an array into a string variable with spaces between each array value? For example, if array() is a text array and has 10 values, array(0) through array(9), with three of those values null, let's say array(3), array(5), and array(7) are null, is there a way to put the remaining seven values into a string variable with spaces between each array value?
I need to get this script to work, I only included what im having the problem with. I am Using jQuery Library. Here is how this should work: .btnRoof div is clicked the parent id is retrieved as var pid a function called roof is called which simply changes a css background to "color" the function perform is called to get the "color1[0]" from the array. My Problem: perform() returns the word color1, color10, color1[0], or c. instead of images/cp-roof-blue.png as listed in the array. Code: $(document).ready(function() { var color1=new Array(); color1[0]="images/cp-roof-blue.png"; color1[1]="images/cp-panel-blue.png"; color1[2]="images/cp-trim-blue.png"; function perform(name, x) { alert(name[x]); //alert([name][x]); //alert(name+'['+x+']'); //alert(color1[0]); // correct return name[x]; } function Roof(color) { $("#colorPicker .roof").css("background", "url("+color+")"); } $('.btnRoof').click(function() { var pid = $(this).parent().parent().attr("id"); Roof(perform(pid, 0)); }); }); I tried to clarify as much as possible, please let me know if I need explain further. Thanks. Hello everyone, I couldn't find anything informative on this subject online. could someone point me to the right direction on how to convert php variable so it could be used in a javascript section. for example I have a php array named $places, it's a nested array and I'd like to traverse through all the elements of this array much like it's done in php =>foreach($places as $place) but this done in JS. in a nutshell how do i convert this variable into a JS appropriate variable. -Thank you the title kind of sums it up... if I have an array of equations (I'm guessing they should be strings but they don't have to be) and a user-defined variable can that variable be used for the "x" in the equations? I already did the easy part ... Code: <!DOCTYPE html> <html> <head> </head> <body> <input onkeyup="solve(this.value)" /><br> <input id="box0" /><br> <input id="box1" /><br> <input id="box2" /><br> <script type="text/javascript"> var equations=["(x*9/5)+32","x+273.15","x-50*(8/13)"] function solve(val){ for (var i = 0; i < equations.length; i++) { document.getElementById("box"+i).value= //ummm... } } </script> </body> </html> I have inherited some code, and cannot get it to work. Note the bold section in the OBJECT tag below. I believe this is where the issue is. Code: <script language="JavaScript"> var camArray = new Array(); camArray['Dolliver'] = "http://video.dot.ca.gov/asx/D5-Bello-at-101.asx"; camArray['Mattie'] = "http://video.dot.ca.gov/asx/D5-Mattie-Rd-at-101.asx"; camera="Dolliver"; var camHTMLd = "<object id='MediaPlayer' width=320 height=240 classid='CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95' standby='Loading Windows Media Player components...' type='application/x-oleobject' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112'><param name='filename' value='"+camArray[camera]+"'><param name='Showcontrols' value='False'><param name='autoStart' value='True'><embed type='application/x-mplayer2' src='"+camArray[camera]+"' width=320 height=240></embed></object>" function changeCam(camera){ document.getElementById("caltransCamera").innerHTML = camHTMLd; //alert(camHTMLd+camArray[camera]); } </script> Then in the page, I have the following code: <a href="javascript:changeCam('Mattie');">101 at Mattie Road</a> It SHOULD open and start displaying the MATTIE cam, but it reloads the default Dolliver. What am I missing? Thank you in advance. 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 Hi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... Hi! I have a javascript in the head of the document which has a variable named "ref2" ... ref2 is already working as I can see its value working in another function. I need to send this variable as the value of a hidden field in the form which is in the body of the document. This is my JavaScript Code: Code: function WriteContactFormStatement1 () { var ContactFormValue = ref2; document.write('<input type="hidden" name="UReferrersName" value="' + ContactFormValue + '" />'); } var WriteContactFormStatement = WriteContactFormStatement1 (); And at the end of my form, before the submit button, I have the following code: Code: <!-- START -- Javascript to print the statement for UReferrersName --> <script language="JavaScript" type="text/JavaScript"> //WriteContactFormStatement(); document.write (WriteContactFormStatement); </script> <!-- End -- Javascript to print the statement for UReferrersName --> When I execute the form, it doesn't work the way it should, plus, gives me a word "undefined" next to the "Submit" button ..... Please help !... - Xeirus. Hello I have a php page in which I declared a js variable... right at the top of the page... <script type="text/javascript"> var tester = 0; </script> Later in the page I test this variable... <script type="text/javascript"> if (tester==1){ do some stuff!! } </script> But I keep getting an error variable _tester undefined Am I missing something obvious... I am new to js... but this seems really straightforward I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? If I manually write out "2/22/2012 4:00 PM" in TargetDate, I get the correct result for what I want to do (a countdown). But I want the countdown to always be the current day at 4pm. So I tried the code below thats commented, but it is not working. New to javascript, still reading the books, just hoping for some guidance on this. Code: Next Update: <script language="JavaScript"> var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() TargetDate = "2/22/2012 4:00 PM"; //TargetDate = "document.write(month + "/" + day + "/" + year) + 4:00PM"; BackColor = "white"; ForeColor = "red"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%H%% H, %%M%% M, %%S%% S"; FinishMessage = "Forecasts posted"; </script> <script language="JavaScript" src="countdown.js"></script> Hello everybody I have a problem with Java Script damned I want to add the values of several variables in one variable and then use this variable, which contains the values of variables You can see the following example HTML Code PHP Code: <input type="text" name="txt1" /> <br/>age <input type="text" name="txt2" /> <br/><br/> <input type="button" name="submits" value="send"/> Javascript Code PHP Code: field = document.getElementsByName('txt1')[0]; field2 = document.getElementsByName('txt2')[0]; submit = document.getElementsByName('submits')[0]; data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; document.getElementsByName('submits')[0].onclick = function(){ alert(data); } After executing this code I find that the variables are not displayed values As in the following picture I want to know what the cause of this problem ? |