JavaScript - Conditional Syntax
I just found this forum! I'm glad because I wanted to ask some javascript questions before.
There was a question at work before at why one would use the following: if (a=='1') ... or if ('1'==a) ... Is there any kind of advantage of using one of the other? Thanks for any response! Similar TutorialsHi could someone help me with this code? What is the correct way to write it. Rules: create an array for the user to type 5 strings in a prompt that will be displayed in an alert box. user must type in the prompt an alert will display what the user typed if the prompt is empty or contains nothing an alert will display telling the user to enter text user clicks ok on the alert box and is sent back to the prompt box Code: function display_moreQuotes(){ var quote2 = new Array(5); var y = 0 for(y=0; y<5; y++) { quote2[y]=prompt('Enter your own quote', ' '); alert(quote2[y]); } if((quote2[y]=' ') || (quote2[y]=null)) { alert("Please enter text"); } } Please explain how/where I went wrong. Thanks! I have two divs, one is the triggering and the other is the hidden one. Hovering the first div will show the hidden div. To hide the div the user must "mouseout" from this div, however if the user "mouseout" from the first div nothing will happend and that is the problem because if there are another group next to them, and the user pass from one triggering div to the next this will show the two hidden divs stacking over one another. This is for a horizontal menu (something like www.oracle.com). The actual code is this: Code: <div id="option_a"><p>FIRST OPTION</p> <div id="option_a_menu"> **HERE ARE LIST, DIVS, IMGS** </div> </div> <div id="option_b"><p>SECOND OPTION</p> <div id="option_b_menu"> **HERE ARE LIST, DIVS, IMGS** </div> </div> The JS: Code: function init() { oOptionA=document.getElementById("option_a"); oOptionAmenu=document.getElementById("option_a_menu"); oOptionB=document.getElementById("option_b"); oOptionBmenu=document.getElementById("option_b_menu"); //behaviors addEvent(oOptionA,'mouseover',goOptionA); addEvent(oOptionAmenu,'mouseout',outOptionAmenu); addEvent(oOptionB,'mouseover',goOptionB); addEvent(oOptionBmenu,'mouseout',outOptionBmenu); } function goOptionA() { oOptionAmenu.style.visibility="visible"; } function outOptionAmenu() { oOptionAmenu.style.visibility="hidden"; } function goOptionB() { oOptionBmenu.style.visibility="visible"; } function outOptionBmenu() { oOptionBmenu.style.visibility="hidden"; } The user will hide the option A menu only when his mouse clears the div that showed up. However is he hover the triggering div and go just to the next triggering div (The second div) will trigger the visibility of their menu, but the previously menu will still on stage, stacking the two menus. I was trying this to solve the problem: Code: ...addEvent(oOptionA,'mouseout',goOptionA); function goOptionA() { if (oOptionAmenu!=hover) { oOptionAmenu.style.visibility="hidden"; } else { oOptionAmenu.style.visibility="visible"; } } However, this is not working, something is wrong with the "oOptionAmenu!=hover" but how can I do this ? Thanks in advanced I wonder if anyone could help me get started with this: I have a website written in a legacy font. I want to give the option to view the same site in Unicode. This would mean transforming about 50 font-glyphs in the html file before it appears in the browser. Now the difficulty is I want this processing only to happen on demand, so the html will still be in the legacy font, and those who need it will be able to use Unicode. I want to do this with an optionally included js file. Can someone give me some idea of how this can be accomplished I will then try and fill in the details. Hi, I'm trying to create a test using Javascript. Actually, I did this in PHP, but we need to put it a server that does nor run it, I think I can convert it to Javascript. I hope it'll be work as in PHP somehow. Test will be composed of 15 questions and each question has either "Yes" or "No" as answer. And, I use radio buttons here for answers. By the way, there will be more than one radio groups. Now, I want to check the value of clicked radio button in each group and use an if-statement to determine if it's correct. And, if it's correct, I want to increment a variable by 1. Finally, by the resulted variable incremented for each question in the test, I want to use another if-statement to show specific result message for and interval of that variable. I tried this for one radio button like this: Code: <script language="JavaScript"> function get(form) { var ans1 = document.form.q1; var score = 0; for( i = 0; i < ans1.length; i++ ) { if( ans1[i].checked && ans1[i].value == no ) { score++; alert(score); } else {alert(score);} break; } } </script> <form name="form" method="get"> <input type="radio" name="q1" value="yes">Yes <input type="radio" name="q1" value="no">No* <input type="button" name="button" value="button" onclick="get(this.form)" /> </form> By the code above, it should alert 1 if "No" is checked and button is clicked and alert 0 if "Yes". This was a preliminary job for me to understand. And I couldn't do even this. Thank you. I'm a beginner and I've gotten myself into a mess, trying to build a page with several dropdowns that change an image conditionally. The idea is: if I pick option b in dropdown a, Picture-A appears. If I go to dropdown 2, and pic option 3, picture-A changes to A3 Or if I pic option 5, picture-A changes to a5. And I want to go in reverse too: if I make a new change to the first dropdown, it would remember what the 2nd option was. But I'm not sure if I've got any syntax worth a dang on this. I've got a mess of a page, he www.mergecreate.com/test25q.html Here's the inline text on the rollover option. It doesn't seem to work: <li><a href="javascriptassit4('6')" onMouseover="change1('pic8','image2')" onclick="if('pic2' == 'image2'){image2.src="images/leaf_shapes/crenate/leaf_elliptic_crenate.gif"};" onMouseout="change1('pic8','image_off');">Test Auriculate overlay</a></li> Hello! I'd like to ask if it is possible to use conditional operators var = condition ? var1 : var 2 to do the same job as the if-else statements I wrote in red below: Thank you! Code: <p id="text">change text colour</p> <br /> <a onclick="allsorting();">sort in both ascending & descending orders</a> <div></div> <script> /* if & else */ function changetext(){ document.getElementById('text').onclick = function (){ swapcolour(this); } } function swapcolour(text){ if(text.style.color == 'black'){ text.style.color = 'red'; } else {text.style.color = 'black'} } window.onload = changetext; </script> Hi everyone, So I know enough to make an image change when you click on something, but not enough to do what I want to do. Code: <img name="ImageState" src="Image1.jpg" alt="Image"> <A HREF="javascript:void(0)" onclick="ImageState.src='Image1.jpg'">Link 1</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image2.jpg'">Link 2</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image3.jpg'">Link 3</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image4.jpg'">Link 4</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image5.jpg'">Link 5</A> The problem is that I want the images to only advance in the proper order. For example, if "Image2.jpg" is currently displayed, I want to make it so that only clicking on "Link 3" will advance it to "Image3.jpg" while the other links are still there but do nothing if you click on them. Can anyone tell me how to do this please? I can't seem to figure out how to do this. I want the user to hit the submit button on the form and then have a few conditional statements ran to if they left any blank textfields and to see if a certain textfield contains numbers. Then I want the user to be directed to a new page if the statements are true. Here is the function code: Code: <script type="text/javascript"> function notEmpty(elem, elem1, elem2, helperMsg, helperMsg2){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); return false;} if(elem1.value.length == 0){ alert(helperMsg); elem.focus(); return false;} if(elem2.value.length == 0){ alert(helperMsg); elem.focus(); return false;} var alphaExp = /^[a-zA-Z]+$/; if(elem1.value.match(alphaExp)){ return true; }else{ alert(helperMsg2); elem.focus(); return false;} return true; } </script> And here is the form code: Code: <center> <div id="main"> <form align="center" method="post" action="/wamp/www/recipesubmit2.php"> <font color="red"><i>* = Required Field</i></font> <table border="0" bordercolor="darkblue"> <tr><td align="right"><font color="red">*</font>Recipe Name:</td><td><input type='text' id='recipeName' size=50></td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Ingredients:</td><td><input type='text' id='ingredients' size=50></td></tr> <tr><td></td><td><font font size="2" color="red">Reminder: </font><font font size="2">Make sure you put a space between each ingredient.</br>Example: <b>chicken cream of mushroom soup</b>. DO NOT PUT</br>MEASUREMENTS! It is also important to correctly spell the</br>ingredients otherwise your recipe may not be found when searched.</td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Directions:</td><td><textarea id='description' cols=50 rows=10></textarea></td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Cook/Prep Time:</td> <td><select name="cooktimedrop"> <option value="zerofive">0-5</option> <option value="sixten">6-10</option> <option value="elevenfifteen">11-15</option> <option value="sixteentwenty">16-20</option> <option value="twentyonetwentyfive">21-25</option> <option value="twentysixthirty">26-30</option> <option value="thirtyonethirtyfive">31-35</option> <option value="thirtysixforty">36-40</option> <option value="fortyonefortyfive">41-45</option> <option value="fortysixfifty">46-50</option> <option value="fiftyonefiftyfive">51-55</option> <option value="fiftysixsixty">56-60</option> <option value="sixtyoneplus">61+</option> </select> minutes</td> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Gen </td> <td><select name="genredrop"> <option value="alcoholic">Alcoholic</option> <option value="appetizers">Appetizers</option> <option value="beverages">Beverages</option> <option value="breads">Breads</option> <option value="breakfast">Breakfast</option> <option value="cakes">Cakes</option> <option value="candies">Candies</option> <option value="casseroles">Casseroles</option> <option value="cookies">Cookies</option> <option value="crockpot">Crockpot</option> <option value="desserts">Desserts</option> <option value="dipsdressings">Dips/Dressings</option> <option value="entrees">Entrees</option> <option value="fatfree">Fat Free</option> <option value="georgeforeman">George Foreman</option> <option value="halal">Halal</option> <option value="herbal">Herbal</option> <option value="italian">Italian</option> <option value="jams">Jams</option> <option value="jello">Jell-O</option> <option value="lowfat">Low Fat</option> <option value="mexican">Mexican</option> <option value="puddings">Puddings</option> <option value="rice">Rice</option> <option value="salads">Salads</option> <option value="sauces">Sauces</option> <option value="seafood">Seafood</option> <option value="snacks">Snacks</option> <option value="soups">Soups</option> <option value="vegan">Vegan</option> <option value="vegetarian">Vegetarian</option> <tr><td></br></td></tr> <tr><td align="right">Submitted By:</td><td><input type='text' id='submittedBy' size=40></br></td></tr> <tr><td></br></td></tr> <tr><td></td><td align="right"><input type='submit' onsubmit="notEmpty(document.getElementById('recipeName'), document.getElementById('ingredients'), document.getElementById('description'),'You have not filled in all required fields.', 'I thought I said no measurements! (No Numbers)')" value='Submit Recipe'></td></tr> </form> </div> </center> Hi, I modified the below code to make a conditional statement. The condition is .. if a user selects Childs_Fullname then the BV_Choice-1 and BV_Choice_2 should be required fields. I am still able to save the form without the above conditional required fields. What am I doing wrong?? Can some point me in the right direction. Thanks Vinny ------------------------------------------------------------------ <script language="JavaScript" type="text/javascript"> function BV_Class_show() { var val = document.getElementById("x_Child1_Fullname").value; if (document.getElementById("x_Child1_Fullname").value != "") { // a name was selected if (document.getElementById("x_Child1_BV_Choice_1") value == "")||(document.getElementById("x_Child1_BV_Choice_2") value == "" )) { // either not selected alert ("You must make a selection from x_Child1_BV_Choice_1 and x_Child1_BV_Choice_2"); return false; } } </script> This is the loop I'm trying to use to check for bullets hitting rocks. the function worked if I used actual numbers instead of the j variable, but I wanted to loop through all the rocks. Can anyone see why the inner function loses the j index and says asteroids[j] is undefined? the hit test is removing the bullets! it's working! the asteroids[j] was used in the hit test! I'm getting testy. LOL Code: for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } Here's the whole script. This is the asteroids script somebody needed help with a few days ago. I just couldn't resist making this. I love asteroids so much it's hard to describe. That game was simply the most awesome thing ever at the time. (I'm a product of the eighties) Code: <html> <head> <title></title> <script type="text/javascript" src="excanvas.js"></script> </head> <body> <script> function pnpoly(xp, yp, x, y){var c=0;for(i in xp){ j=i++;if((((yp[i]<=y)&&(y<yp[j]))||((yp[j]<=y)&&(y<yp[i])))&&(x<(xp[j]-xp[i])*(y-yp[i])/(yp[j]-yp[i])+xp[i])){c =!c}} return c} var canvas = null; var c2d = null; //... window.onload = init; function init() { thrustFlame=false asteroids = [{ x: 470, y: 290, angle: 1.71, inertia: .5, inertiaAngle: 1.2, points_x: [-30, -27, 5, 15, 30, 15,-5], points_y: [ -5, 15, 30, 27, -5, -25, -30], hits:0 }, { x: 270, y: 290, angle: 1.71, inertia: .75, inertiaAngle: 1.9, points_x: [-30, -10, 0, 20, 40, 20, -10], points_y: [0, -20, -50, -30, 0, 20, 20], hits:0 }] player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0, bullets:[] } canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); setInterval(step, 60); } function step() { for (i in asteroids) { asteroids[i].angle += i % 2 == 0 ? .05 : -.05 asteroids[i].x < 0 ? asteroids[i].x = canvas.width : asteroids[i].x %= canvas.width asteroids[i].y < 0 ? asteroids[i].y = canvas.height : asteroids[i].y %= canvas.height asteroids[i].x += Math.sin(asteroids[i].inertiaAngle) * asteroids[i].inertia; asteroids[i].y += -Math.cos(asteroids[i].inertiaAngle) * asteroids[i].inertia } ctx.fillStyle = "rgb(0,0,0)" ctx.fillRect(0, 0, canvas.width, canvas.height); for (u = 0; u < asteroids.length; u++) { ctx.save(); ctx.beginPath() Asteroid_draw(asteroids[u]); ctx.closePath(); ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore(); } ctx.save(); ctx.beginPath() Player_draw(player); ctx.closePath() ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore() if(thrustFlame){ ctx.save(); ctx.beginPath() Player_drawFlame(player); ctx.closePath() ctx.strokeStyle = "#ff0000"; ctx.stroke(); ctx.restore() thrustFlame=false } player.x < 0 ? player.x = canvas.width : player.x %= canvas.width player.y < 0 ? player.y = canvas.height : player.y %= canvas.height if (player.inertia > .025) player.inertia -= .025 player.x += Math.sin(player.inertiaAngle) * player.inertia; player.y += -Math.cos(player.inertiaAngle) * player.inertia for(i in player.bullets){ player.bullets[i].timer++; if(player.bullets[i].timer > player.bullets[i].range)player.bullets.shift() player.bullets[i].x < 0 ? player.bullets[i].x = canvas.width : player.bullets[i].x %= canvas.width player.bullets[i].y < 0 ? player.bullets[i].y = canvas.height : player.bullets[i].y %= canvas.height player.bullets[i].x += Math.sin(player.bullets[i].inertiaAngle) * player.bullets[i].inertia; player.bullets[i].y += -Math.cos(player.bullets[i].inertiaAngle) * player.bullets[i].inertia ctx.save(); ctx.beginPath() ctx.fillStyle="rgba(255,255,0,1)" ctx.arc(player.bullets[i].x,player.bullets[i].y,1.5,0,3.14,true) ctx.fill() ctx.closePath() ctx.restore(); } for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } } } function Asteroid_draw(obj) { ctx.translate(obj.x, obj.y) ctx.rotate(obj.angle); ctx.moveTo(obj.points_x[0], obj.points_y[0]); for (i = 0; i < obj.points_x.length - 1; i++) { ctx.lineTo(obj.points_x[i], obj.points_y[i]); } ctx.lineTo(obj.points_x[0], obj.points_y[0]) } function Player_draw(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); //Points {0,-12}{7,5}{-7,5} ctx.moveTo(0, -12); ctx.lineTo(7, 4); ctx.lineTo(-7, 4); ctx.moveTo(-7, 4) ctx.lineTo(0, -12); } function Player_drawFlame(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); ctx.moveTo(-2, 2); ctx.lineTo(0, 12); ctx.lineTo(2, 2); } document.onkeydown = function (event) { keyDown(event) }; function keyDown(event) {event=!event?window.event:event if (event.keyCode == 32) { player.bullets.push({x:player.x,y:player.y,inertia:player.inertia+10,inertiaAngle:player.angle,timer:0,range:40}) } if (event.keyCode == 37) { player.angle -= .1 } /*left*/ else if (event.keyCode == 39) { player.angle += .1 } /*right*/ else if (event.keyCode == 38) { thrustFlame=true var x1= Math.cos(player.inertiaAngle)* player.inertia; var y1= Math.sin(player.inertiaAngle)* player.inertia; var x2= Math.cos(player.angle)* .2; var y2= Math.sin(player.angle)* .2; var xR= x1 + x2; var yR= y1 + y2; var lengthR= Math.sqrt(xR*xR+yR*yR); if (lengthR==0){angleR=0} var angleR= Math.acos(xR/lengthR); if (yR<0)angleR= 0-angleR; player.inertia=lengthR // player.inertiaAngle = (player.inertiaAngle*19 + player.angle) / 20 player.inertiaAngle =angleR } /* up*/ else if (event.keyCode == 40) { player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0 } } /*down*/ } </script> <canvas id="canvas" width="600" height="600"></canvas> </body> </html> Hello, First, thank you to anyone that can help. Basically I am trying to create a Cascade Dropdown with a submit button, that once clicked, takes them to a URL depending on the choices they made in the cascade dropdown. I have the cascade dropdown working properly but do not know how to create a submit button that says, "If Cookeville = Cosmetology; then go to this URL." Any ideas or suggestions? I will need to create this type of conditional statement for each choice. My code so far is below. Thank you again in advanced. Code: <form id="locations"> <label for="categories">categories: </label> <select name="categories" id="categories"> <option value="1">Cookeville, TN</option> <option value="2">Lebanon, TN</option> <option value="2">Dalton Beauty School</option> <option value="2">Daphnie</option> </select> <label for="items">items: </label> <select name="items" id="items" type="submit"> <option class="2" value="0">Cosmetology</option> <option class="2" value="1">Cosmetology Instructor</option> <option class="2" value="2">Instructor Trainee</option> <option class="1" value="3">Cosmetology</option> <option class="1" value="4">Cosmetology Instructor</option> <option class="1" value="5">Esthetician</option> <option class="1" value="6">Instructor Trainee</option> <option class="1" value="7">Nail Technology</option> </select></form> <script type="text/javascript"> //Applies cascading behavior for the specified dropdowns function applyCascadingDropdown(sourceId, targetId) { var source = document.getElementById(sourceId); var target = document.getElementById(targetId); if (source && target) { source.onchange = function() { displayOptionItemsByClass(target, source.value); } displayOptionItemsByClass(target, source.value); } } //Displays a subset of a dropdown's options function displayOptionItemsByClass(selectElement, className) { if (!selectElement.backup) { selectElement.backup = selectElement.cloneNode(true); } var options = selectElement.getElementsByTagName("option"); for(var i=0, length=options.length; i<length; i++) { selectElement.removeChild(options[0]); } var options = selectElement.backup.getElementsByTagName("option"); for(var i=0, length=options.length; i<length; i++) { if (options[i].className==className) selectElement.appendChild(options[i].cloneNode(true)); } } //Binds dropdowns function applyCascadingDropdowns() { applyCascadingDropdown("categories", "items"); //We could even bind items to another dropdown //applyCascadingDropdown("items", "foo"); } //execute when the page is ready window.onload=applyCascadingDropdowns; </script> This is what I'm trying to do. CONDITIONS: If a person selects a Friday Class but not a Saturday Class the Total Cost Field will automatically enter $99. If a person selects a Saturday Class but not a Friday Class the Total Cost Field will automatically enter $99 as well. If a person selects both a Friday & Saturday Class the Total Cost field will automatically be $159. I found the following code and so far only have it changing when a Friday class is entered. I have no idea where to go from here. Please help. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Test</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> </head> <body> <div> <p><span class="style1">Friday Class:</span> <select id="fridayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> <p> <span class="style1">Saturday Class:</span> <select id="saturdayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> </div> <div><span class="style1">Total Cost:</span> <input type="text" id="totalCost"/></div> <script> window.onload = function () { var friday = document.getElementById('fridayClass'), saturday = document.getElementById('saturdayClass'); friday.onchange = function () { totalCost.value = '$99.00'; }; }; </script> Fellow Coders, I am trying to follow this tutorial (http://econym.org.uk/gmap/basic16.htm) What I would like to do is have in my XML file, a parameter for a total (some random number) and I want to plot a marker based on this number. So like, if the total="5" then marker would be red, if it was 10, marker would be green. I see in the tutorial that they are storing the possible markers in an array, I get that. What I don't know how to do is plot the markert depending on the value of the total field in the XML file. Hi all, I had posted earlier on the NaN issue. I have worked some more on my test file. Basically I want the user to select an option depending on whether he/she has Paracetamol in syrup or drops form. Once this is selected, automatically a different div for syrup or for drops should be seen depending on what the user selected earlier. After this on pushing the calculate button, the output should be appropriate depending on the strength of the solution either for drops or syrup. I have put together what I think code that should work but it stubbornly refuses to do otherwise. I have attached the relevant file. If it doesn't work, obviously there is something wrong but what it is eludes me. Any help will be appreciated greatly, Thanks, Hi All! Thanks in advance to any and all who help me. What we are trying to do is have a form where customers can use a conditional logic based form that upon submission will redirect to checkout with an appropriate product bundle being populated in the shopping cart. I have some experience with creating forms, in fact I have made a decent form that I have modified from an online form builder... the problem is I have no idea how to auto-fill the shopping cart... period. From what I have read in my research this should be a function of Javascript. I have a decent working knowledge of php, and html, but I am pretty clueless when it comes to Javascript, if anyone could point me in the right direction for this project I would really appreciate it. this is my javascript code: Code: var aaa, aab; aaa = choo.chooserver0.checked; aab = choo.chooserver1.checked; k=(aaa==true)?0:(aab==true)?1:(aaa=true&&aab==true)? 'b2' : false ; now when the checkbox with id chooserver0 is checked, it sets k's value to 0, and when checkbox with id chooserver1 is checked it sets its value to 1, but when both are checked it must set value to b2, but it sets value to 0, why? and when i write it as: Code: var aaa, aab; aaa = choo.chooserver0.checked; aab = choo.chooserver1.checked; k=(aaa=true&&aab==true)? 'b2' :(aaa==true)?0:(aab==true)?1: false ; when box 1 is checked, it sets k= false, when box2 is checked it sets k= 'b2' and when both are checked it sets k = 'b2'... why is code doing so? Hi, I have a form setup so that selecting a radio button opens a specific text field. The problem is if the user starts to enter information, then switches to a different radio button (perhaps they chose the wrong radio to start), the text they already started to enter on the previous textfield doesn't get cleared. This will be a problem later when inserting to sql. Here is a summary of the code: Code: <head> <script type="text/javascript"> function doClick(objRad){ if (objRad.value=="0"){ document.getElementById("textbox").style.display='block'; } else{ document.getElementById("textbox").style.display='none'; } if (objRad.value=="1"){ document.getElementById("textbox1").style.display='block'; } else{ document.getElementById("textbox1").style.display='none'; } if (objRad.value=="2"){ document.getElementById("textbox2").style.display='block'; } else{ document.getElementById("textbox2").style.display='none'; } } </script> </head> <body> <form action="insert.php" method="post"> <p>Please choose the business type: <input type="radio" name="rad" value="0" onclick="doClick(this)"> Sole Proprietorship <input type="radio" name="rad" value="1" onclick="doClick(this)"> Partnership <input type="radio" name="rad" value="2" onclick="doClick(this)"> Corporation <div id="textbox" style="display:none"> <input type="text" name="txt"> This is my sole proprietorship info.</div> <div id="textbox1" style="display:none"> <input type="text" name="txt"> This is my partnership info.</div> <div id="textbox2" style="display:none"> <input type="text" name="txt">This is my corporation info. </div> </form> </body> Any help is appreciated, Thanks in advance! I know only basic Javascript. I'm making a choose-your-own-adventure game, but want parts of each "page" to display conditionally. For example: You see a sword, a hat, and a helmet here. Take sword Wear hat Wear helmet Continue into swamp Clicking "Take sword" would set a variable "haveSword" to true, and the page would display: You heft the sword, testing its razor edge against your thumb. You see a hat and a helmet here. Wear hat Wear helmet Continue into swamp It tells you the results of your action, then repeats the main part, but updated to reflect any changes. If you then pick "Wear helmet," it shows the action and main paragraph, but updated to reflect that change, etc., all in any order that you choose. This is a simple example, but I would like a system that allows for more complex interactions, that you can perform all in the same "room." Later on in the adventure, when you enter the dragon's lair, you get a page detailing the encounter: if you have the sword, you can attack the dragon, or else you get a paragraph about being powerless. The dragon attacks you, and if you have the helmet, it protects you; if you only have the hat, you get a sentence about it going up in flames before you die; and if you have neither, you just die. The concept is pretty simple, but I don't know how to code it cleanly in Javascript. I currently have each "page" contained in a hidden <div> tag with its own id. I put them in the body instead of as vars in the script because fiction has lots of single and double quotes which need escaped and make it hard to type and read (e.g., \"How\'re you doin\'?\" he asked.). I'd like to keep it that way, but maybe that's unrealistic. I have two placeholder divs in the body. OnLoad puts the first "page" of the adventure into placeholder2 using innerHTML. Clicking on a link in the text, like "Take sword," puts "You heft the sword..." into placeholder1 and refreshes the text of placeholder2. But I need that text to stop displaying the "Take sword" option if "haveSword" is now true, and not mention the sword in the room description... A different story that shows what I'm looking for, but is unfinished and unsustainably messy, can be found at http://taleofwayfinder.webs.com/red_0_2.html tl;dr How can I insert a paragraph using innerHTML (or whatever method) and have it evaluate what parts/options to display when it inserts? I've got a slide toggle script online and have got just one bit that I cannot figure out why. What is (toggled = !toggled)? What does it mean? Does that mean toggled = false? But I tested it, it seems not like that. And once the slide is toggled, it should use the minheight. Then the condition for var Height must be the opposite of (toggled = !toggled). Then what is (toggled = !toggled) like? Is that like (toggled != !toggled)? Code: <!DOCTYPE html> <html> <head> <title>Avinash</title> <style> #slider { margin:0px auto; padding:0px; width:400px; border:1px solid #000; background:#0f0; height:0px; overflow:hidden; } </style> <script> var minheight = 0; var maxheight = 1000; var time = 1000; var timer = null; var toggled = false; window.onload = function() { var controler = document.getElementById('slide'); var slider = document.getElementById('slider'); slider.style.height = minheight + 'px'; controler.onclick = function() { clearInterval(timer); var instanceheight = parseInt(slider.style.height); var init = (new Date()).getTime(); var height = (toggled = !toggled) ? maxheight: minheight; var disp = height - parseInt(slider.style.height); timer = setInterval(function() { var instance = (new Date()).getTime() - init; if(instance < time ) { var pos = Math.floor(disp * instance / time); result = instanceheight + pos; slider.style.height = result + 'px'; document.getElementById('log').innerHTML = 'Current Height : <b>' + result + " " + disp + '</b><br /> Current Time : <b>' + instance + " " + pos + '</b>'; }else { slider.style.height = height + 'px'; //safety side ^^ clearInterval(timer); controler.value = toggled ? ' Slide Up ' :' Slide Down '; document.getElementById('log').innerHTML = 'Current Height : <b>' + height + '</b><br /> Current Time : <b>' + time + '</b>'; } },1); }; }; </script> </head> <body> <h1> Toggle Slide </h1> <input type="button" id="slide" value =" Slide Down "/> <span id="log" style="position:absolute; left:10px; top:150px;"></span> <br /> <div id="slider"> content goes here </div> </body> </html> I'm a PHP guy and haven't used jQuery much. I have a script I found in a book and I am trying to get working and am having trouble. It's a drop down list. I am using it in place of an HTML select box, so I want to pass the value selected from the list along with the form in a hidden field. My question is how do I extract the value out of the JS function and get it into the hidden field? Code: $(document).ready(function() { createDropDown(); $(".dropdown dt a").click(function(event) { event.preventDefault(); var dropID = $(this).closest("dl").attr("id"); $("#" + dropID).find("ul").toggle(); }); $(document).bind('click', function(e) { var $clicked = $(e.target); if (! $clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide(); }); $(".dropdown dd ul a").click(function() { var dl = $(this).closest("dl"); var dropID = dl.attr("id"); var text = $(this).html(); var source = dl.prev(); $("#" + dropID + " dt a").html(text); $("#" + dropID + " dd ul").hide(); source.val($(this).find("span.value").html()) }); }); function createDropDown() { var selects = $("select.dropdown_value"); var idCounter = 1; selects.each(function() { var dropID = "dropdown_" + idCounter; var source = $(this); var selected = source.find("option[selected]"); var options = $("option", source); source.after('<dl id="' + dropID + '" class="dropdown"></dl>'); $("#" + dropID).append('<dt><a href="#">' + selected.text() + '<span class="value">' + selected.val() + '</span></a></dt>'); $("#" + dropID).append('<dd><ul></ul></dd>'); options.each(function() { $("#" + dropID + " dd ul").append('<li><a href="#">' + $(this).text() + '<span class="value">' + $(this).val() + '</span></a></li>'); }); idCounter++; }); } |