JavaScript - Return True And Return False -- What Means What?
Hi room,
Hey, I opened up the source code for this page in google chrome and since i'm learning javascript, i wanted see if i could "read" it and figure out what was going on. I'm am having the hardest time understanding "return false" and "return true". Could someone step me through this via interpreting this code (in bold typeface): Code: var DefaultValue = 'Search'; function clearSearch() { if (document.searchForm.q.value == DefaultValue) { document.searchForm.q.value = ''; } } function validateSearchHeader() { if ( document.searchForm.q.value == '' || document.searchForm.q.value.toLocaleLowerCase() == DefaultValue.toLocaleLowerCase() ) { alert('Please enter at least one keyword in the Search box.'); document.searchForm.q.focus(); return false; } return true; } Thanks! Similar TutorialsI don't understand the logic of Break, Return False, Return True. It was never really covered in our college class, and I see everyone using it. I got an A in the class, if that 'proves' that I really tried to apply myself. NOTE: I understand what the function is doing. I just don't understand WHEN to use break, return false or return true if the the translator can determine the conditional statements. PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } else return false; } if the the translator can determine the conditional statements, why not write it like this: PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; // what's the point for the 'break'? Won't the rest of the code be ignored since it passed the first condition? } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } // why not leave the last else out? is it just a 'safety' catch, in case something other than true or false is inputted? else return false; // what's the point? } Questions: Why use return true, if the translator knows it's ture? Why use "return false" if the translator knows it's false and the alert window has already gone up? why not use "break" to stop the code? Why use the "return false" at the end "else" statement? hi peeps, this one might be confusing, if so i apologise! below is a cut down version of the script calling a function: Code: function updateStockRequest(thestatus,theform,thedate) { if(thestatus == 'locked') { if(checkStockRequested()) { if(confirm('Are you sure you want to send for processing?\nYou will not be able to add any more stock!')) { document.getElementById('status').value = 'locked'; document.forms[0].submit(); } } else { alert('You must request some stock first!'); } } } the following is the function being called: Code: function checkStockRequested() { //check to see if stockrequest has items added!!! xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var params = "?theuid=" + escape(document.getElementById('uid').value); var url="_check_stockrequest.php" url=url+params; ajaxedInner = ""; xmlHttp.open("GET",url,true); xmlHttp.setRequestHeader("If-Modified-Since", "Fri, 31 Dec 1999 23:59:59 GMT"); xmlHttp.onreadystatechange=stateChanged; xmlHttp.send(null); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4){ if (xmlHttp.status == 200) { responsestring = xmlHttp.responseText.replace(/^\s+|\s+$/g, ''); alert(responsestring); if(responsestring == 'true') { return true; } else { return false; } } } } } in the testing the function is alerting 'true' but the calling function still fails and says you need to add stock. i must admit ive rarely used the return syntax so maybe im doing it wrong?!? ive tried many variants such as creating a variable and assigning it the string 'true' etc and then using if(checkStockRequested == 'true') but it still fails. help!!!!!!!!! Hi All, This is in ASP.Net Im creating a task loggin system and this allows the user to raise tasks and update them, im using javascript for validation and if the fields are empty it then changes the fields back ground to Red which is fine but then it goes on to update the data in SQL which i dont want, any suggestions or how i can achieve no post back is the result from the function is False (for fields in error) Html Code where im calling the function Code: <asp:button runat="server" id="btnChangeCommentsAuth" CSSclass="RaiseButton" OnClientClick="CommentsCheck('MainDisplayContentChange_txtAuthCommentsArea');" PostBackUrl="~/RaiseTaskChange.aspx" Text="Auth" /> Javascript function Code: function CommentsCheck(comments) { var com; var result = new boolean(); com = document.getElementById(comments); if (document.getElementById(comments).value == '') { com.style.backgroundColor = "#B20635"; result = 0; } else { result = 1 } } Thanks in Advance look forward to your reply. Got a timing issue with sending a URI string out to a server side script right before a client side form validation process returns true.. The problem is that the return true gets called to quickly for the submission of the URI string to be completed. So my question is, might there be a way to mix a return and a setTimeout? If so, could some one give a an example? Thanks! Hi all, I have a page built with asp.net that includes some "imagebutton"s within a form. These render as input tags with the type set to image. I ahve the onclick attribute set to run a custom javascript function and return false, so in the fully rendered page I get something like the following: Code: <input type="image" name="ctl00${cut}" tabindex="-1" title="Click to look up the details" src="images/load_details.png" onclick="LoadDetails(); return false;" style="border-width:0px;" /> This has worked fine for the few months the code has been in place and then just recently (within the last few days) it has stopped working for a single network user. They click on the link and instead of the function executing (and the AJAX loading details into the page) the form submits. This makes me think that the "return false" simply isn't executing. The user says that they haven't changed any settings or anything that may cause this issue... The browser being used throughout the company is IE8 under Windows XP. I have checked the version being used on their comptuer and it is 8.0.6001.18702, which is the same version as the one installed on my local machine... which is working fine. Another user has logged into the computer being used by the user with the issues and it works fine for the second user. Also, the user having the issues has logged into a different computer on the network and was still having the same problems. I think I've included all the details, but I'll happily provide any required information. Anyone have any ideas? I have the following form: Quote: <form action="/cgi-bin/script.cgi" method="POST" onsubmit="check_create()"> <fieldset> <legend>Create project</legend> Type <input id="type" type="text" name="type" size="20" /><br/> Name <input id="project" type="text" name="project" size="20" /><br/> Language to use <input id="language" type="text" name="language" size="20"/><br/> <input type="hidden" name="profile" value="[% profile %]"/> <input type="submit" value="Create" /> </fieldset> </form><br/> and check_create function is: Quote: function check_create() { var type = document.getElementById('type').value; var pname = document.getElementById('project').value; var language = document.getElementById('language').value; if ((type == '') || (pname == '') || (language == '')) { alert('You must complete form'); return false; } else alert('Ok'); } The problem is that return false doesn't work, but form lanch /cgi-bin/script.cgi. Where is the problem? Why return false doesn' work? Regards, savio Hi I've managed to change the border color whenever someone clicks on another link on my page but because I need to use return false to keep the color it is stopping the link from going to that page; Code: <script type="text/javascript"> function changeColor(color) { document.getElementById("nav").style.borderColor = color; } </script> <a href="index.php" onclick="changeColor('red') ;return false">HOME</a> <a href="about.php" onclick="changeColor('blue') ;return false">ABOUT</a> <a href="contact.php" onclick="changeColor('orange') ;return false">CONTACT</a> Any help would be appreciated, I've only recently got into JS Cheers hi guys, i need a javascript for my checkbox 1st: need to check the checkbox to go to next page or else stay at current page with an alert popout "Please check the checkbox" can some one help me please? I am trying to figure out that if the function "xmlhttp.onreadystatechange=function()" returns true the whole function "function checkUser(str)" should return true as well....so not sure how to do it. i have banged my head since long so please advise! Here is the code below: -------------------------------------------------------- function checkUser(str) { var sp = document.getElementById("msgs"); if (str=="") { document.getElementById("msgs").innerHTML="Username cannot be empty."; return false; } if (str.length <= 6) { document.getElementById("msgs").innerHTML="Username cannot be less than 6 characters and must not start with a number or a special value"; return false; } if (window.XMLHttpRequest) { //code for IE7+, firefox, chrome, opera, safari xmlhttp=new XMLHttpRequest(); } else { //code for old IE xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { if (xmlhttp.responseText === 'FOUND') { sp.style.color = "red"; sp.innerHTML = "[ERROR]: The username \"" + str + "\" already exist. Please try a different name."; return false; } else if (xmlhttp.responseText === 'NOT FOUND') { sp.style.color = "blue"; sp.innerHTML = "Username: VALID"; return true; } } } xmlhttp.open("GET", "checkUser.php?q="+str,true); xmlhttp.send(); } hi guys, maybe im being stupid but any ideas why this doesnt seem to work: Code: function checkSCItems() { //check sccost not blank due to ajax need to do lookup xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var params = "?scnumber=" + escape(document.getElementById('scnumber').value); var url="_check_scitems.php"; url=url+params; ajaxedInner = ""; xmlHttp.open("GET",url,true); xmlHttp.setRequestHeader("If-Modified-Since", "Fri, 31 Dec 1999 23:59:59 GMT"); xmlHttp.onreadystatechange=stateChanged; xmlHttp.send(null); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4){ if (xmlHttp.status == 200) { var checkSCItemsResponse = xmlHttp.responseText; if(checkSCItemsResponse == 'found') { return true; } else { window.location.hash = 'scpricebuildup2'; alert('You must first create some cost items'); return false; } } else { alert('There was a problem, please try again, or contact the Administrator'); return false; } } } } im calling this and if it returns true another function is called but for some reason the 2nd function never seems to happen. (that function works fine so it cant be that - if i just set this function to return true everything works fine too) its being called like so: Code: <a href='javascript:;' onclick="if(checkSCItems() && validateText(document.subcontract_order,['scdate','scworks','scpayment','scfirstpayment','scpaymentinterim','scbalance','scretentionat','sccommence','sccompletion','sclabour','scplant','scmaterials']) && validateDate(document.subcontract_order, ['scdate','scfirstpayment','scbalance','sccommence','sccompletion']) && validateSelectNoBlank(document.subcontract_order, ['trading_name'])){window.open('subcontract_order_print.php?id=<?php echo writeIfSet($id) ?>')}"> is there some issue with ajax and return true? do i need to tell it to call another function that calls return true etc? I am having trouble with some JavaScript that is supposed to add some Google Analytics tracking parameters to "cross-domain" links (used to auto append tracking info across multiple domains as a way of sharing the Google cookie info). I have my code kind of working at this point except the default event (the normal href link) is not stopping. Instead my new event (the link plus Google parameters) fires off and is immediately replaced by the default (no parameters) event. For links that open in a new window, two windows open, one the standard link and one with the intended parameters. I am using a return false; on each link type but it is not doing anything. Any ideas how I can stop the default event? Code: Code: //Last Updated 5/10/12 /*Regex list of on-site domains, pipe and backslash delimited. */ var wa_onsiteDomains = /mydomain\.com|my2nddomain\.com|my3rddomain\.com|javascript/i; /*Used to unobtrusivly add events to objects*/ function unobtrusiveAddEvent (element,event,fn) { var old = (element[event]) ? element[event] : function () {}; element[event] = function () {fn(); old();}; } function wa_crossDomainLink(i) { return function () { var thisLink = decodeURI(wa_links[i]); var thisLinkTarget = wa_links[i].target; if (typeof(_gaq) == "object") { if(thisLinkTarget == "_blank") { var wa_myTracker=_gat._getTrackerByName(); var wa_fullUrl = wa_myTracker._getLinkerUrl(thisLink); window.open(wa_fullUrl); return false; } else { _gaq.push(['_link', thisLink]); return false; } } }; } var wa_links = document.links; if ( wa_links ){ for(var i=0; i<wa_links.length; i++) { if( wa_links[i].href.match(wa_onsiteDomains) && !wa_links[i].href.match(location.hostname)){ unobtrusiveAddEvent( wa_links[i], 'onclick' , wa_crossDomainLink(i)); } } } Note, the code above resides in a separate js file and is called at the bottom of every page. Thanks! Lets say I have a MySQL value of 4... and I have a HTML INPUT field.. Is there a way to make it so that if a client tries to submit a value higher than 4, then they will be returned a message? Something like: Code: <SCRIPT type="text/javascript"> function validateForm() { if (document.forms["form"]["quantity"].value== (+$row['quantity']) { alert ("Cannot submit because the quantity specified is not available."); return false; } } </SCRIPT> <INPUT name="quantity" onsubmit="return validateForm()> I am getting double Alert prompts for a single form: The alert pops up the first time, then when I click OK, the same one pops open again. I think my code should do the alert once when it hits "else window.alert(sameWarning) and the stop when it reaches "return false()"; but it seems return false() is causing the alert twice. Maybe because I have two forms on one page; yet, they have two separate function names ("signinForm()" and "saveSignUp()")and call two separate forms (forms[0] and forms[1])? I think my code is correct, but I can't figure it out at this point. Any help would be appreciated. Thanks in advance! Code: <script type="text/javascript"> //FIRST FUNCTION FOR FORMS[0] function signinForm(){ // var sameWarning = "The required fields were not submitted for the following error(s). \n \n"; var warningLogin = "The following field(s) require an entry: \n \n"; var sameWarning = warningLogin; var userName = document.forms[0].userName.value; var pswd = document.forms[0].pswd.value; if(userName == ""){ sameWarning += " - First Name \n"; } if(pswd == ""){ sameWarning += " - Password \n"; } if (warningLogin == sameWarning){ return true; } else { window.alert(sameWarning); } return false; } //SECOND FUNCTION CALL FOR FORMS[1] function saveSignUp(){ // var warning = "The required fields were not submitted for the following error(s). \n \n"; var warning = "The following field(s) require an entry: \n \n"; var same = warning; var firstName = document.forms[1].firstName.value; var lastName = document.forms[1].lastName.value; var email = document.forms[1].email.value; var phone = document.forms[1].phoneNumber.value; if(firstName == ""){ //firstName.style.backgroundColor="red"; warning += " - First Name \n"; } if(lastName == ""){ warning += " - Last Name \n"; } if(email == ""){ warning += " - Email \n"; } if(phone == ""){ warning += " - Work Phone \n"; } if(phone < 5 ){ warning += " - Must be a numberssss \n"; } if (warning == same){ return true; } else { alert(warning); } return false; } </script> HTML Code: <h1>Login</h1> <form method="post" onsubmit="return signinForm();" action="" > <input type="text" placeholder="Username/Email" name="userName"> <input type="password" placeholder="Password" name="pswd" id="pswd"> <input type="submit" onclick="signinForm();" value="Sign In"> </form> <h1>Sign Up!</h1> <form method="post" onsubmit="return saveSignUp()" action="" > <input type="text" placeholder="First Name" name="firstName"> <input type="text" placeholder="Last Name" name="lastName"> <input type="text" placeholder="Email" name="email"> <input type="text" placeholder="Phone Number" name="phoneNumber"> <input type="submit" onclick="saveSignUp();" class="button wide" value="Request an Account"> </form> *UPDATE Fixed! After I removed the onclick in the button, the double alerts went away. Apparently, I was I was firing off two events (calling the javascript twice) with both the onsubmit and the onclick. Just wondering: 1. Is "onsubmit" a special event handler just for button "type=submit" vs onlclick can be used for any element? 2. Is there a preference among developers to use onclick vs. onsubmit? 3. Is there an order of precedence for method calls over submit calls (the onclick goes first, then it automatically fires the submit call to the function too)? i'm trying to get some information with this code from my database: Code: function getTableSize(tableName){ db.transaction ( function(tx) { tx.executeSql ('SELECT * FROM '+ tableName,[] , function(tx, r) { return r.rows.length; } ); } ); } but it doesnt work and i cant figure why what i want is that this function return the table size to one variable in another function...something like: Code: var groupTableSize = getTableSize('groups'); i have this in my javascript code but have no idea on how a returned value works/where does it return to???? what do i do/or can i do with a value that gets returned??? i am asking this so i can learn on how to use it cos i am new to all this and dont know how it works...please show/explain to me please? thanks here my full code: PHP Code: <?php use_stylesheets_for_form($form) ?> <?php use_javascripts_for_form($form) ?> <html> <head> <script type="text/JavaScript"> function refreshPage(s) { window.location.reload(); if((s.options[s.selectedIndex].value) = "zed-catcher") { var $index = s.selectedIndex; var $value = s.options[$index].value; alert (s.selectedIndex); alert ($value); window.location.reload(); [COLOR="Red"]return &value; //where does it return to ???? how/what to do with a return value???[/COLOR] } } </script> </head> </html> <body> <form action="<?php echo url_for('adminservice/'.($form->getObject()->isNew() ? 'create' : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" '?>> <?php if (!$form->getObject()->isNew()): ?> <input type="hidden" name="sf_method" value="put" /> <?php endif; ?> <table > <tfoot> <tr> <td colspan="2"> <?php echo $form->renderHiddenFields(false) ?> <a href="<?php echo url_for('adminservice/index') ?>">Back to list</a> <?php if (!$form->getObject()->isNew()): ?> <?php echo link_to('Delete', 'adminservice/delete?id='.$form->getObject()->getId(), array('method' => 'delete', 'confirm' => 'Are you sure?')) ?> <?php endif; ?> <input type="submit" value="Save" /> </td> </tr> </tfoot> <tbody> <?php echo $form->renderGlobalErrors() ?> <tr> <th><?php echo $form['name']->renderLabel() ?></th> <td> <?php echo $form['name']->renderError() ?> <?php echo $form['name']?> </td> </tr> <tr> <th><?php echo $form['logo_url']->renderLabel() ?></th> <td> <?php echo $form['logo_url']->renderError() ?> <?php echo $form['logo_url'] ?> </td> </tr> <tr> <th><?php echo $form['call_center_number']->renderLabel() ?></th> <td> <?php echo $form['call_center_number']->renderError() ?> <?php echo $form['call_center_number'] ?> </td> </tr> <tr> <th><?php echo $form['catcher_id']->renderLabel(); $catcher_id = $form->getObject()->getCatcherId(); $catcher = LpmCatcherPeer::getByCatcherId($catcher_id); $catcher_name = $catcher->getName(); ?></th> <td> <?php echo $form['catcher_id']->renderError() ?> [COLOR="Red"]<select name="services" onchange="refreshPage(this.form.services)">[/COLOR] <?php $catcher_names = LpmCatcherPeer::getByAllNames(); foreach($catcher_names as $row) { ?> <option value="<?php echo $row->getName()."/".$row->getId();?>" <?php if($row->getName() == $catcher_name) echo ' selected="selected"'; ?> ><?php echo $row->getName();?></option> <?php } [COLOR="Red"]if ($row->getName() == "zed-catcher") //just thought with the return in my java script i can pass the newley selected value back to here and if it meets the if i echo these lines?? { echo $form['service_code']->renderLabel(); echo $form['service_code']->renderError(); echo $form['service_code']; } [/COLOR] ?> </select> </td> </tr> <tr> <th><?php echo $form['price_description']->renderLabel() ?></th> <td> <?php echo $form['price_description']->renderError() ?> <?php echo $form['price_description'] ?> </td> </tr> </tbody> </table> </form> </body> thanks! Hello, How can this be made to return confirmation? <form id="score_form" method="post" action="addscore.php"><input id="score" name="score" value="" type="hidden"><img id="collect" style="cursorointer;height: 37px; width: 100px; margin-top: 13px;" src="./collectlive.gif" onclick="collect_points();"></form> Letsay the confirmation window would say"ARE YOU SURE" hi,i don't understand about the jquery basic example the code is below PHP Code: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $('p').addClass(function(n){ return 'par_' + n; }); }); }); </script> <style type="text/css"> .par_0 { color:blue; } .par_1 { color:red; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Add classes to p elements</button> </body> </html> i want to understand about the how is work function(n){ in the function a and how work return function return 'par_' + n; thanks mate Have a jsp page with 10 editable fields and in last Add Button.Now when user edit a field from value 10 to 20(example)and click on Add .Value will be changed and focus will return to the same field.similarly for other fields.how to to .any code sample?
hi, i wanna get the value from javascript to php variable. here is my code, <html> <body> <select name="drop" size="10" onchange="drp_selectd_value(this)"> <option>One</option> <option>Two</option> <option>Three</option> <option>Four</option> <option>Five</option> </select> <?php echo "The PHP value".'<script>value_return();</script>'; $p='<script>y;</script>'; ?> </body> </html? <script> var x; var y=100; function drp_selectd_value(sdf) { x=sdf.value; alert("Value is : " +x); value_return(x); } function value_return(val) { alert("Second Function calling : "+val ); return val; } </script> This code does not working!!! How can i fix tis problem???I m expecting for the reply.. Thanks in advance |