JavaScript - How Do I Declare An Empty Array?
How do i declare an empty array?
I need to iterate through a group of arrays and search for a user-chosen word every time. The problem is i can't declare how many array elements will be needed, such as: new array = (12), because some words inside my arrays, occur more than others. So i need to decalare an empty array with x number of possible values. Can this be done? Similar TutorialsSo here's my problem. I have a long list of buttons that I want to declare their onclick with values from an array. It looks something like this. It seems simple but obviously there's something that I'm not seeing that isn't allowing this to run.Here's what the code looks like Code: <html> <body> <form name="form1"> <input type="button" name="one"> <input type="button" name="two"> <input type="button" name="three"> </form> <script> function hello() { .... .... } goodbye = ["one","two","three"] for(i=0;i< 3; i++) { document.form1.goodbye[i].onclick=hello; } If anybody could help me out with this I would greatly appreciate it. What type of variable is an empty array element? i thought it was undefined, but i noticed that they have different behavior than undefined does: Code: var r=Array(1); var s=r.concat([0,"",null,undefined]); alert (s.toSource()) //==="[, 0, "", null, (void 0)]" typeof s[0] //==="undefined" typeof s[4] //==="undefined" as you can see, 0 and 4 both === undefined. yet, they don't have the same toSource()... why? is this special type named anything specific? or more importantly, can it be detected outside of an array as being distinct from undefined? EDIT: im thinking this would be the same type as ({}).nonProp ... i guess the question is actually, "can you tell the difference between uninitialized and undefined"? Is there a built in method to remove empty array elements
anotherVar should be -1 if there are no matches, but it doesn't seem to work
PHP Code: var string = "abadafa"; var matches = string.match(/a/gi); //doesn't work with /z/ for example var anotherVar = matches.length || -1; The default operator should return the second value if the first is null or false, and according to PHP Code: try { alert(matches.length); } catch (e){ alert(e); //alerts null } it's null. fyi: http://helephant.com/2008/12/javascr...ault-operator/ What's going on? THIS IS NOT HOMEWORK Hi all, Simple question: Is it "legal" to conditionally declare variables? For example: First Code: if (name) { var age = 54; var year = 1957; } Second Code: var age; var year; if (name) { age = 54; year = 1957; } Is "First" wrong and "Second" right? Or are they both equally OK? Thanks. -- Roger Edit: Please explain your answer. I have been working on a few budget scripts that I can access from the web in using HTML. My problem is that when variable values change I need to change these values in all of the HTML files on the server. I know that there is a way to declare global variables in a single file and use those values in another file but I have not been able to find any information that tells me exactly how to do this. I have tried to put it together on my own using what little informaiton I have been able to find but have not been able to get this to work. Is there a more detailed referance that I can find somewhere or does anyone know what steps I need to take to make this happen?
Okay so I have a form, and it has many options and the ability to select more than one. I can get a txt input div to show up if "Other" is selected with the below Javascript, but i need to add something else to the underlined area below, which will say something like "if which.value == "other" || "other" & "anything else", show the div." ...for you see, the div disappears again if you select "other" in addition to another option. Code: function showBox(which) { var d = which.id; if (d == "Referred_by") {var b = 1} if (d == "Bit_Rate") {var b = 2} if (d == "Samp_Rate") {var b = 3} if (d == "format") {var b = 4} if (d == "extension") {var b = 5} if (d == "turnaround") {var b = 6} if (d == "language") {var b = 7} if (which.value == "Other") { document.getElementById("inputBox" +b).style.display="block"; } else { document.getElementById("inputBox" +b).style.display="none"; } } help is appreciated! Hello I am building a registration page . If the user completes all the required field i load the info into the database but if there are missing fields I combined some javascript into php to display next to the empty field a note that it should be filled. This is my code : Code: <?php if (isset($_POST['submit'])) { $username =$_POST['username']; $password =$_POST['password']; $password2 =$_POST['password2']; $firstname =$_POST['firstname']; $lastname =$_POST['lastname']; $email =$_POST['email']; $address =$_POST['address']; $city =$_POST['city']; $state =$_POST['state']; $zip =$_POST['zip']; $dob =$_POST['dob']; if (empty($username)){ ?> <script language="javascript"> var user =true </script> ;<? } if (empty($password)){ ?> <script language="javascript"> var pass =true </script><? ; } And it goes on................... Then next to the inpput box I display a text in case the user didn't fill in the info like this and by the way the above code is in my validate.php page wich i include in the main registration page Code: <?php include ('includes/validate.php');?> <form action="registration.php" method= "post" > <fieldset> <legend>sitename Registration</legend> <p> <label for"username">Username</label> <input type "text" name=username /> <script type="text/javascript"> if (user == true) { document.write("Please enter a Username of your choice"); } </script> </p> <p> <label for"password">Password</label> <input type "password" name=password /> <script type="text/javascript"> if (pass == true) { document.write("Please choose a Password"); } </script> </p> <p> <label for"password2">Re-type Password</label> <input type "pass2" name=password2 /> <script type="text/javascript"> if (pass2 == true) { document.write("Please re-type your Password"); } </script> </p> And it goes on......for the rest of the input fields. I need some help with a solution for when the user fills in the info and pushes the "register" button the page refreshes and it whipes all the info the user already input but it does display the warnings where the user didn't input any data, so what would be the best way to go to keep the data that the user entered.Thank you. Hey guys, Is there a way of hiding a whole table row if a certain cell inside it is empty? Thanks, Adam Hi i would like to know how to check for any check boxes that are empty if any is empty then i want the code to stop were its at and go no ferther and prompt a message somthing missing?
Hello, I'm trying to compare a <div> background color with another color. However, on FireBug, I noticed that my <div> doesn't have a background color code in it (I placed document.getElementById(o) on watch), even though I have already specified on my css. As a result, I'm comparing an empty string with another color code. Why is this so ? Javascript: Code: function highlight(o) { var color1; color1 = document.getElementById(o).style.backgroundColor; if (color1.compareColor("#0072BC")) { document.getElementById(o).style.backgroundColor="#f8951e"; } else if(color1.compareColor("#f8951e")){ document.getElementById(o).style.backgroundColor="#0072BC"; } } HTML: Code: <div class="nav-tab" id="home"><a href="#" onmouseover="highlight('home')" onmouseout="highlight('home')" >Home</a></div> Hi. I have a form and if a field is blank a message pops up. This doesnt stop my php from running though and takes the user to another page. Is there a line to keep them on that page untill all fields are filled out? code so far is simple. <script type="text/javascript" language="JavaScript"> function nameempty() { if ( document.form.subject1.value == '' ) { alert('No name was entered!') return false; } } </script> //then down the bottom I have a small bit that implements that code Tearing my hair out here. I've got a table where I'm trying to append additional input and file fields when someone clicks a link. The appending works fine, but when I click submit, none of the appended values are being passed through. I've tried it two different ways (both being appended to the "moreSwatches" table cell: Code: function addSwatch2() { var moreSwatches = document.getElementById('moreSwatches'); imgBox = document.createElement("input"); //imgBox.type = 'file'; //imgBox.name = 'swatch[]'; imgBox.setAttribute("type","file"); imgBox.setAttribute("name","swatch[]"); moreSwatches.appendChild(imgBox); textBox = document.createElement("input"); textBox.type = 'text'; textBox.name = 'swatchname[]'; moreSwatches.appendChild(textBox); setBR = document.createElement("br"); moreSwatches.appendChild(setBR); } function addSwatch() { var moreSwatches = document.getElementById('moreSwatches'); var newDiv = document.createElement("div"); addText = '<input type="file" name="swatch[]" style="width: 300px"> <input name="swatchname[]" size="25"><br>'; newDiv.innerHTML = addText; moreSwatches.appendChild(newDiv); } If I hardcode a second set of inputs below the first, it works fine. Anything that is appended is getting ignored. Anyone got any ideas? Hey folks. I currently have a PTZ camera that is taking screenshots every minute (or so) and sending a copy of that image (overwriting the previous one) to my website. Basically, the visitors to the website will be greeted with a live screenshot. The problem is if the visitor hits the website at just the right time, the screenshot won't be loaded completely while the 2nd most screenshot is being overwritten... creating an empty image load (the dreaded red X). What I am looking to do with Javascript is to be able to load a generic image in the scenario in which no image loads. Is that possible? I tried doing something like the following and onload-ing it, but it wouldn't work. Any help would be appreciated. Thanks! Code: <script type="text/javascript"> <!-- function replaceSrc() { var images = document.getElementsByTagName('img'); for(var i = 0; i < images.length; i++) { var img = images[i]; if(img.src.length == 0) { img.src = 'images/garbage.gif'; } } } --> </script> How to get this to work? Code: <html> <body> <script type="text/javascript" src="01.js"> <h1>Welcome</h1> <a href="#" onclick="write(); return false;">Click here</a> <div id="info_here"> </div> </body> </html> 01.js Code: function write() { var a=document.getElementById("info_here"); a.innerHTML=document.write("Hello <br />" + "Thanks for clicking"); } Hi guys, I am using jquery ui to have two connected sortable lists. The first list is available numbers, and the second is selected numbers. Everything with the jquery is working fine. The problem i am having is when i try to get the contents of the selected numbers box, it is empty, even though the sortables are or were dragged to that list. I tried using this... Code: var response = $("#selected_numbers_box").val(); alert( response ); and I also tried this.. Code: var response = $("#selected_numbers_box").html(); alert( response ); both are empty. What i am trying to do is retrieve the values of the new list "Selected numbers Box". Any suggestions? My code was taken directly from the jquery ui tutorial. Thanks in advance. Hi, I am not able to calculate the offsetwidth of the element which contains extra space in between the characters. for ex. if the element contains "A A" as a innerHTML value - if we calculate offsetwidth as 29 and also if the element contains "A A" value again I am getting the same offsetwidth as 29. While calculating the offsetwidth it is not calculating the empty space. May I know how to calculate the offsetwidth with the empty space because I need to insert the ellipsis (...) if it exceeds original width? Code snipet function fitStringToWidth(title,width,className) { var span = document.createElement("span"); span.className="titleBar-Title-1"; span.style.display='inline'; span.style.visibility = 'hidden'; span.style.padding = '0px'; document.body.appendChild(span); var result = title; span.innerHTML = result; alert("Offsetwidth : " + span.offsetWidth); .......................... } Thanks in advance. Arthik Hi there, I have this form that validates a few textboxes & a dropdownlist. And when it is not filled in, the border of the textboxes and dropdownlist would turn red, followed by an alert message notifying which field have not been filled in. Else, the border will revert back to black, and the form will be submitted successfully. Right now, I would like to prevent the user from entering blanks (like entering a space to cheat the system). How should I tweak the codes to make it work? Javascript Code: function check(checkForm) { var fields = new Array("Name","Email Address", "Domain Name"); var index = new Array(),k=0; for(var i=0;i<fields.length;i++) { var isFilled = false; var c = document.getElementsByName(fields[i]); for(var j = 0; j < c.length; j++) if(!c[j].value == "") { isFilled = true; c[j].className = "defaultColor"; } else { c[j].className ="changeToRed"; } if(!isFilled) { index[k++] = fields[i]; } } if(k>0) { joinComma = index.join(', '); alert('The field(s) corresponding to '+ joinComma + ' is/are not selected.'); return false; } } HTML Code: * Name: <input type="text" id="Text27" name="Name" /><br /> <br /> *Email Address: <input type="text" id="Text28" name="Email Address" /> @ <select id="Select5" name="Domain Name"> <option></option> <option>hotmail.com</option> <option>yahoo.com</option> </select> <input id="Submit5" type="submit" value="Submit" onclick="return check(checkForm)"/> Hi. I have a form and in the form is a checkbox use as a switch to hide and unhide a two textbox. When the other textbox is hide, the other is unhide such as the code below. When the user click the submit button on the first time and there is an error, it reloads and the id="fieldset.-in_honor" hide because it is set to hide initially but not empty. My problem is, I want to show the fieldset whichever is not empty after submit button is click and there is an error so user will not enter any more information to the other field. Is that possible? Please help. I have a hard time explaining it but hopefully you will get the idea. Thanks in advance and hope to hear from you as soon as possible. Code: /*toggle switch*/ <p><input type="checkbox" name="in_honor" value="" id="checkmemoriam" onclick="showHide(this.name);" />Please check to make this donation in honor of someone special.</p> /*hide textbox but unhide when the switch is on or the checbox is check*/ <fieldset id="fieldset-in_honor" class="fieldgroup" style="display:none"> <legend class="hide">In Honor Of</legend> <p>To make this donation in honor of someone special, please complete the two fields below:</p> <div class="formfield" <?php echo highlight('donate_honor_name'); ?>> <label for="donate_honor_name">Name:</label> <input id="donate_honor_name" name="donate_honor_name" class="text" type="text" value="<?php safeEcho($form['donate_honor_name'])?>" /> <?php helper_error('donate_honor_name'); ?> </div> <div class="formfield" <?php echo highlight('donate_honor_acknowledgement'); ?>> <label for="donate_honor_acknowledgement">Acknowledgement should be sent to:</label> <textarea id="donate_honor_acknowledgement" name="donate_honor_acknowledgement"><?php safeEcho($form['donate_honor_acknowledgement'])?></textarea> <?php helper_error('donate_honor_acknowledgement'); ?> </div> /*always show on first load of the page but once the checkbox is check, will need to hide and delete info entered*/ <fieldset id="fieldset-in_registration"> <label for="impact" style="font-weight:bold">B. Impact Areas</label> <table> <tr> <td style="width:380px;text-align:left"><label for="d" id="deslist4" name="deslist4">Crime and Drug Use <a href="javascript:alert('Ensuring prevention and treatment programs and appropriate support services are available to people who are at risk for drug addiction and supporting efforts to reduce crime.');">what is this?</a></label></td> <td style="float:right"> $<input id="d" name="d" class="text" type="text" value="<?php safeEcho($form['d'])?>" style="width:90px;" onChange="CalculateTotal()" /> <?php helper_error('d');?> </td> </tr> <tr> <td style="width:380px;text-align:left"><label for="e" id="deslist5" name="deslist5">Early Childhood Development <a href="javascript:alert('Children are healthy, loved, nurtured, safe and have access to quality childcare and early education. This includes programs that increase parenting skills, providing books to all children and providing developmental screening for 3 and 4 year olds.');">what is this?</a></label></td> <td style="float:right"> $<input id="e" name="e" class="text" type="text" value="<?php safeEcho($form['e'])?>" style="width:90px;" onChange="CalculateTotal()" /> <?php helper_error('e');?> </td> </tr></table> Code: /*JAVASCRIPT FUNCTION*/ function showHide() { if (document.getElementById('checkmemoriam').checked) { if (document.getElementById('TotalC').value == "0.00") { document.getElementById('fieldset-in_honor').style.display=""; // this is for showing document.getElementById('fieldset-in_registration').style.display="none"; } else { var answer = confirm("You entered a total gift designation of $" + document.getElementById('TotalC').value + ". At this time, gifts made \"in honor of someone special\" are not eligible for the designation option. Clicking the OK button will delete all your designation(s). Do you want to continue?") if (answer) { document.getElementById('TotalC').value="0.00"; document.getElementById('d').value="0"; document.getElementById('e').value="0"; document.getElementById('fieldset-in_honor').style.display=""; // this is for hiding document.getElementById('fieldset-in_registration').style.display="none"; } else { document.getElementById('checkmemoriam').checked=false; } } } else { if ((document.getElementById('donate_honor_name').value="") && (document.getElementById('donate_honor_acknowledgement').value="")) { document.getElementById('fieldset-in_honor').style.display="none"; // this is for hiding document.getElementById('fieldset-in_registration').style.display=""; } else { var answer = confirm("The field you are trying to close will delete all information you entered \"in honor of someone special\" but it will allow you to designate. Clicking the OK button will show the designation list. Do you still want to continue?") if (answer) { document.getElementById('donate_honor_name').value = ""; document.getElementById('donate_honor_acknowledgement').value = ""; document.getElementById('fieldset-in_honor').style.display="none"; // this is for hiding document.getElementById('fieldset-in_registration').style.display=""; } else { document.getElementById('checkmemoriam').checked=false; document.getElementById('fieldset-in_honor').style.display=""; // this is for showing document.getElementById('fieldset-in_registration').style.display="none"; } } } } 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. |