JavaScript - If Statement To Check Whether A String Is A String Is Returning False
Hey all, I have a simple example below showing how when I pass in the value of the value attribute of option node, and then use if operator to check whether parameter is a string or not, even though it's a string, it converts it to false boolean and triggers the else statement rather than calling a function:
Code: <body> <select> <option value="createMsg">Add Message</option> <option value="removeMsg">Remove Message</option> </select> </body> Code: var menu = { handleMenu : function(callback){ if(callback === "string"){ menu[callback](); } else { console.log("Issue occurred") } }, createMsg : function(){ var content = document.createTextNode("Please give additional information."), heading = document.createElement("h1"); heading.appendChild(content); document.body.appendChild(heading); }, removeMsg : function(){ } } document.getElementsByTagName('select')[0].onchange = function(){ menu.handleMenu(this.value)}; callback should be a string so why is it saying otherwise? Thanks for response Similar TutorialsHi everyone, I have a hunch that my function is not returning the string value. Below runs some information about the code: getvalues_2() - A function that recognizes the value of the string selected by the user from the drop down list and sends it to a variable. Variable name is 'groom_profession' here. Based on the value (text) returned, it assigns a particular number to the variable 'profession' in this case. But, I have been noticing that irrespective of the value chosen from the drop down list, the variable 'profession' is assigned a default value from the switch case statement. I know the variable (textval_2) is able to store the correct value from the drop down list with the help of an alert command. But, it fails while returning the value. I even tried initializing the string in the function body but to no avail. What could be wrong here? Following is the code for one of the drop-down lists: Code: <b> Groom's current Profession </b> <FORM NAME="Profession"> <SELECT NAME="Groomprofession" onchange = "getvalues_2()"> <OPTION VALUE="c1">Select </OPTION> <OPTION VALUE="c2">Doctor </OPTION> <OPTION VALUE="c3">Engineer </OPTION> <OPTION VALUE="c4">Lawyer </OPTION> <OPTION VALUE="c5">CA </OPTION> <OPTION VALUE="c6">IAS </OPTION> <OPTION VALUE="c7">Engineer + MBA </OPTION> <OPTION VALUE="c8">Family Business </OPTION> <OPTION VALUE="c9">None of the above </OPTION> </SELECT> </FORM> Following is the code for function getvalues_2() declaration: Code: <script type = "text/javascript"> function getvalues_2() { var val_2 = document.Profession.Groomprofession.value; var si_2 = document.Profession.Groomprofession.selectedIndex; if (si_2 != 0) { var textval_2 = " "; textval_2 = document.Profession.Groomprofession.options[si_2].text; //alert (val_2); // for testing //alert (textval_2); // for testing return (textval_2); } } </script> Following is the code for the switch case statement: Code: <script type="text/javascript"> var profession; groom_profession = getvalues_2(); switch(groom_profession) { case "Engineer" : profession = 1.8; break; case "Doctor" : profession = 1.9; break; case "Lawyer" : profession = 1.65; break; case "CA" : profession = 1.7; break; case "IAS" : profession = 2.0; break; case "Family Business" : profession = 1.5; break; case "Engineer + MBA" : profession = 1.95; break; case "None of the above" : profession = 1.95; break; default: profession = 0.6; } </script> The website has a total of 11 drop-down lists (so 11 functions like getvalues, and 11 switch case statements. I thought if I could get one to work, the others might follow suit too). I would be really grateful if someone could look into my problem and suggest where I am going wrong. Thanks a lot! I need to check if a var (lessonnum) is a string that cannot be converted to a number, i.e. "fred" "george" "catalyst" etc. but not "5" "456" or "34564" etc.: Code: var lessonnum = readCookie('lesson'); if ((intro != "12")||((lessonnum != "A STRING THAT COULD BE A NUMBER"))){ do sth. } How could I do that? string check in javascript do suggest me something ....... if you have any two words like , "me" and "you". Basically I have this: function semaphore(phrase) { var len = phrase.length; var str1 = ""; for (var i=0;i<len;i++) { if(phrase[i]=" ") { phrase[i] = "interval"; } var str = "images/semaphore/" + phrase[i] + ".gif"; str1 = str1 + "<img src='" + str + "'>"; } return str1; } so if phrase = i love coding forums I want all the spaces to be replaced with the text "interval" Thanks Danny Here is the code i am trying. Code: var str="اسدف"; patt=/[\u0600-\u06FF\u0750-\u077F]/; result=patt.test(str); document.write("<br />Returned value: " + result); </script> This should return true, as the string in the str variable is indeed Arabic character. But it returns false. Need some help here on this.. Thanks in Advance I have thought about using the standard email checker pattern but we have had problems in the past so looking to check if the string follows these simple rules. has no spaces, has a character/s at the start followed by an @ then has a character/s followed by a (dot) then another character/s i.e a@a.a aa@aa.aa aaa@aaaaaaaaa.aaa i am not sure how the standard pattern works but feel that it may be to complex which causes some email address to fail. Function findsometing() ( var myString = 'results' + '<BR>' for (var initiator, test condition,incrementor.) { if (.....) { myString ='some quote'; } else if (.....) { myString += something + '<br>' } else if (....... ) { myString += something + '<br>' } else { myString += ''; } } displayMessage(myString) ) I am a complete newbie to javascript and programming, so excuse any faux pas, but I want to check the myString variable after all the loops in the for loop statement have been completed. For example if nothing was added to the var myString after the completeion of the for loop, i want to display a message that no results found. i tried various attempts of an if statement along lines of } } if (myString = 'results') ....i also tried if myString= ('results' + '<BR>') { displayMessage('no results found') } else { displayMessage(myString) } ) Any pointers as to where i am going wrong? Hi Guys, This isn't the first time I've posted about cookies, and I apologize for that. My cookies were working perfectly until I made some changes to the site (ie. ran it through w3 validation). Now they aren't writing. I can't find any bugs with firebug, and I've tried following it through line by line. I expect my email validation is returning false, and I would really appreciate if you can help me find the bug. Here's the code, which I call with onsubmit="return Getvalue()" The rest of the page is at www.saverally.com Code: function echeck(str) { var at="@" var dot="." var lat=str.indexOf(at) var lstr=str.length var ldot=str.indexOf(dot) if (str.indexOf(at)==-1){ return false } if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){ return false } if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){ return false } if (str.indexOf(at,(lat+1))!=-1){ return false } if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){ return false } if (str.indexOf(dot,(lat+2))==-1){ return false } if (str.indexOf(" ")!=-1){ return false } return true } function ValidateForm(emailID){ //var emailID=document.frmSample.txtEmail if ((emailID.value==null)||(emailID.value=="")){ showDialog('Uh-oh.','Our tech-pigeons say you must enter an email address.','success',3); emailID.focus() return false } if (echeck(emailID.value)==false){ emailID.value="" showDialog('Uh-oh.','Our tech-pigeons say you must enter a "proper" email address.','success',3); emailID.focus(); return false } return true } /*Email Validation*/ function Getvalue() { var validation=ValidateForm(document.getElementById("email")); if(validation==true) { user_email=document.getElementById("email").value; createCookie("userEmail",user_email,365); document.addform.submit(); return true; } else { return false; } } </script> Hi, In the attached code the outcome always defaults to the first test, even if the condition is false. How would I alter the syntax so that both condtions are evalauted? Code: var res = document.calc.num1.value*100/document.calc.num2.value; function cost1() { if (isNaN(res)) { document.calc.result1.value=0; } else { document.calc.result1.value=document.calc.num1.value*100/document.calc.num2.value; } } Thanks Iain 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. Not sure if I even ask correctly. Excuse the poor PHP man for not knowing javascript. I need to add a check to this code. It picks up an image when you click on it, then puts it down when you click again. What it needs is another check WHERE (on what) have you clicked to put it down. If it's a particular DIV then OK. If not (if elsewhere) don't put it down and don't change the click counter. Code: <html> <head> <style type="text/css"> .drag { position: relative; height:56px; width:56px; background-color:#FF0000; color:White; } </style> <script type="text/javascript"> var _startX = 0; // mouse starting positions var _startY = 0; var _offsetX = 0; // current element offset var _offsetY = 0; var _dragElement; var _oldZIndex = 0; // we temporarily increase the z-index during drag var _debug; var _countClick = 0; InitDragDrop(); function InitDragDrop() { document.onclick = OnMouseClick; document.onMouseClick = OnMouseClick; } function OnMouseClick(e) { debugger; _debug = $('debug'); // if first click this is zero if (_countClick == 0) { // IE if (e == null) e = window.event; // IE uses srcElement, others use target var target = e.target != null ? e.target : e.srcElement; _debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked'; // for IE, left click == 1 // for Firefox, left click == 0 if ((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag') { // grab the mouse position _startX = e.clientX; _startY = e.clientY; // grab the clicked element's position _offsetX = ExtractNumber(target.style.left); _offsetY = ExtractNumber(target.style.top); // bring the clicked element to the front while it is being dragged _oldZIndex = target.style.zIndex; target.style.zIndex = 10000; // set _dragElement for next click _dragElement = target; // tell our code to start moving the element with the mouse document.onmousemove = OnMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function() { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; //set click count to 1 so we know next click is to release _countClick = 1; // prevent text selection (except IE) return false; } } if (_countClick == 1) { if (_dragElement != null) { _dragElement.style.zIndex = _oldZIndex; // we're done with these events until the next OnMouseDown document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; // this is how we know we're not dragging _dragElement = null; _debug.innerHTML = 'mouse up'; } //set click count back to 0 so next we know it's first click again _countClick = 0; } } function OnMouseMove(e) { if (e == null) var e = window.event; // this is the actual "drag code" _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')'; } function ExtractNumber(value) { var n = parseInt(value); return n == null || isNaN(n) ? 0 : n; } // this is simply a shortcut for the eyes and fingers function $(id) { return document.getElementById(id); } function OnMouseUp(e) { } </script> </head> <body> <div id="thediv" class="drag" style='background: url(shield.gif) no-repeat center top;'></div> <pre id="debug"> </pre> <div id="slot1" class="dropon" style='position: absolute; height:28px; width:28px; top: 200px; left: 200px; background-color:#FF0000; color:White;'></div> <div id="slot2" class="dropon" style='position: absolute; height:28px; width:28px; top: 200px; left: 230px; background-color:#FF0000; color:White;'></div> </body> </html> I need help with the following code below. It just doesn't turn out okay. Any ideas? Code: function changing() { A = document.exempel.Amount.value B = ("<%#Container.DataItem("Price_2_qty")%>") C = ("<%#Container.DataItem("Price_3_qty")%>") D = ("<%#Container.DataItem("Price_4_qty")%>") E = ("<%#Container.DataItem("Price_5_qty")%>") if (A < B) {document.exempel.Price.value = "<%#Container.DataItem("Price_1")%>"} else if (A = B && (!(A >= C))) {document.exempel.Price.value = "<%#Container.DataItem("Price_2")%>"} else if (A = C && (!(A >= D))) {document.exempel.Price.value = "<%#Container.DataItem("Price_3")%>"} else if (A = D && (!(A >= E))) {document.exempel.Price.value = "<%#Container.DataItem("Price_4")%>"} else if (A >= E) {document.exempel.Price.value = "<%#Container.DataItem("Price_5")%>"} } I am trying to use some string functions with no results. It appear what I'm using them on are not strings. my_string = document.getElementById("link5").onclick; document.write(my_string.lastIndexOf("5")); This gets nothing! And document.write(document.getElementById("link5").onclick.lastIndexOf("5")); gets nothing. BUT if I make a string and put what the onclick is set to with: my_string = "function onclick(event) { reveal(\"5\", \"2\", \"1864\")"; then my_string.lastIndexOf("5") will yield 34. So why is my original my_string = not working? And how can I get it to work? I was looking at this page, and came across "%" used in strange context. It appears that the mod operator can be used in Strings?? http://download.oracle.com/javase/tu...vaOO/enum.html What does this do/ mean? Thanks!!: System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); This is probably easy if I knew Javascript. Can someone show me the code to get the number "800014352" part from the url???? http://testebiz/ebizbtest/ShoppingCa...2/Default.aspx Hi, I have a string stored in a variable var = "4.25 houses". I would like to only extract the currency value, ie "4.25" from this. Is this possible? Also I would like to divide and multiply the new variable I get... does this number need to be converted or something? Thanks in advance! Hi everyone... I'd written a code to split a string like below: Input string: a=>aa|b=>b||b|c=>cc and the output: a=>aa b=>b||b c=>cc I use .Match() to do that as below: var matches = "a=>aa|b=>b||b|c=>cc".match(/(?:[^|]|\|\|)+/g) I want to use tha .Split() to split the above string. please help me... This is all php except for the java code I am struggling with. Please advise. I have tried this 2 ways and have spent hours on something that should be simple. I have a string that I am trying to display in an alert box with an onclick method 1: $mystring = "<a href=\"mysite.com\">Click</a>"; this does not work echo "<input type='button' value='Grab Code' onClick=alert('$mystring')>"; nor does this echo "<input type='button' value='Grab Code' onClick=alert('".$mystring."')>"; nor does anything I try. All I want to do is display the value of mystring in an alert box. However, this does work .. echo "<script type='text/javascript'> alert('".$mystring."');</script>"; But I cannot call this from an onclick. Any help is appreciated. Thanks JT |