JavaScript - How To Return A True Or False Value From A Function To Disable Automatic Postback
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. 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 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! 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!!!!!!!!! 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(); } 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? 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? 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 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! 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 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 hello, only just starting using javascript, so question may not make sense but il try anyway. if i group some javascript into a function that returns false; how could i carry that 'false' out of the function so it can be used outside the function. the example below shows the validate function checks for a condition then returns false if it is met. i want this false to then be passed out of the function to then throw an error in its containing function. (goal to prevent the submitting of a form) if (checBox =="1"){ validate(); } function proceed(); function validate() { if (chilD1.value >70) { alert("Please enter your Childs correct Age"); return false; chilD1.focus(); } } i dont want the proceed function to be called, so how can the other function prevent this. Now i realise that the validate function could be incorporated into the top level function but, my form will eventually be quite large with a multiplitude of fields so i need to know how i can call back to functions and use them as objects insteasd of repeating lots of code. Hope you can help thanks. Hi, hope someone can help. doing some work with google maps api. I have a function called codeaddress, this is triggered by a search button. is there a way to add js to make an automatic click on results after search ? here is code of function.. Code: function codeAddress() { var address = document.getElementById("address").value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); map.setZoom(10); } else { alert("City was not found: " + status); } }); } I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? actually, the subject pretty much is the question, but if you want more detail, here goes: the below function: Code: function centerAndZoom(line) { bounds = line.getBounds(); map.setCenter(bounds.getCenter(map), map.getBoundsZoomLevel(bounds)); } pans and zooms the map when the user selects a line, which is really useful about 95% of the time and kind of annoying 5% of the time. So I was thinking it would be good to give them the option of disabling that function for the 5%. the function gets called from a couple of different places in the code, so for neatness' sakes it would be nice to have something within the function above that checks for the checkbox state before executing. but some kind of if/else where the function gets called would be ok, too... I'm not really fussy. thanks in advance. |