Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Javascript If Else Statement

Posted on 2011-02-14
11
Medium Priority
?
626 Views
Last Modified: 2012-05-11
What is the correct format to write javascript code that has an if else element to it? I have a form that is programmed in Java and each question on the form is broken up into sections. At the end of each section you have many options you can A.go on to next section B.save and exit form or C. write in javascript if there is more than one way to handle the question. An example of this is: If yes, go to next question, if no, jump to section 5. How would I write this portion of code in javascript?
0
Comment
Question by:anshealth
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 9

Assisted Solution

by:CCSOFlag
CCSOFlag earned 664 total points
ID: 34892384
not entirely sure what you are wanting, but no there is not a "goto" in javascript.  You need to use if else statements combined with functions to do what you want.

For example:

function Section5()
{
...code...
}

if (A)
{
...some code...
}
else if (B)
{
...some code...
}
else
{
  Section5();
}
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 34892407
Further info on this page: http://www.w3schools.com/js/js_if_else.asp
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 668 total points
ID: 34894421
@anshealth your question is very poorly worded and has no example code. If I were to ask the same question I would do something like

In the following html I have a form with several sections. After each section I need to have 3 choices
1) go to next section
2) save and exit and
3) write ???

<form>
part 1:
<input type="..." />

part 2:
<input type="..." />

part 3:
<input type="..." />
</form>

How do I write a function that.....

-----------------------

And please use the Code link under the comment box to put in code, or wrap in [ code ] code here [ /code ] like
this example here

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 20

Expert Comment

by:Proculopsis
ID: 34894706

Here's a sample if else:

  if ( option == "next" ) {
    announce( "You selected 'Go to next section'." );
  } else {
    if ( option == "save" ) {
      announce( "You selected 'Save and Exit'." );
    } else {
      if ( option == "write" ) {
        announce( "You selected 'Write'." );
      }
    }
  }

Open in new window


...but if you have many options then you might want to consider a switch statement:

  switch ( option ) {
    case "next":
      announce( "You selected 'Go to next section'." );
    break;
    case "save":
      announce( "You selected 'Save and Exit'." );
    break;
    case "write":
      announce( "You selected 'Write'." );
    break;
  }

Open in new window


Here is a full working example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_26821019.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

jQuery(document).ready( function () {

  $("input.action").click( action );

});

function action() {
  var option = $(this).attr("id");

  switch ( option ) {
    case "next":
      announce( "You selected 'Go to next section'." );
    break;
    case "save":
      announce( "You selected 'Save and Exit'." );
    break;
    case "write":
      announce( "You selected 'Write'." );
    break;
  }

/* ***********************
  if ( option == "next" ) {
    announce( "You selected 'Go to next section'." );
  } else {
    if ( option == "save" ) {
      announce( "You selected 'Save and Exit'." );
    } else {
      if ( option == "write" ) {
        announce( "You selected 'Write'." );
      }
    }
  }
*********************** */

}

function announce( message ) {
  $("#result").text( message );
}

</script>
</head>
<body>

<input id="next" class="action" type="button" value="Next section" />  
<input id="save" class="action" type="button" value="Save and exit" />  
<input id="write" class="action" type="button" value="Write" />  

<fieldset><legend>Result</legend><span id="result">Click a button...</span></fieldset>

</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34894739
Keen, are we?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34906406
What about an object like this one ?
The number of each choice is the index of the next question(section)
var questions = [
	{
		"question":"What is your sexe",
		"choices": [{"Male":4}, {"Female":1}]
	},
	{ 
		"question":"Have you ever acouchi??",
		"choices": [{"Yes":2}, {"No":4}]
	},
	{ 
		"question":"How many children?",
		"choices": [{"Less or equal than 2":4}, {"More than 2":3}]
	},
	{ 
		"question":"At the same time?",
		"choices": [{"Yes":4}, {"No":4}]
	},
	{ 
		"question":"Test ended\nDo you want to restart it?",
		"choices": [{"Yes":5}, {"No":null}]
	}
	];

Open in new window

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 668 total points
ID: 34907668
Check this :


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<head runat="server">
    <title>Question/Answer</title>
    <script language="javascript" type="text/javascript">
        var nextQuestionIndex = 0
        var questions = [{"question":"What is your sexe?","choices":[{"Male":4},{"Female":1}]},{"question":"Have you ever acouchi?","choices":[{"Yes":2},{"No":4}]},{"question":"How many children?","choices":[{"Less or equal than 2":4},{"More than 2":3}]},{"question":"At the same time?","choices":[{"Yes":4},{"No":4}]},{"question":"Test ended<br />Do you want to restart it?","choices":[{"Yes":0},{"No":-1}]}];
        var answers = [];
        window.onload = nextQA;

        function nextQA() {
            var choicesTable = document.getElementById("choices");
            var inputs = choicesTable.getElementsByTagName("input");
            for(var i=0;i<inputs.length;i++) {
                if(inputs[i].type=="radio" && inputs[i].checked) {
                    saveAnswer(inputs[i]);
                    nextQuestionIndex = inputs[i].value;
                }
            }
            if(nextQuestionIndex>=0) {
                if(nextQuestionIndex == 0) answers = [];
                document.getElementById("question").innerHTML = questions[nextQuestionIndex].question;
                while(choicesTable.rows.length>0) choicesTable.deleteRow(0);
                for(var i=0;i<questions[nextQuestionIndex].choices.length;i++) {
                    insertNewRowInTable(choicesTable, questions[nextQuestionIndex].choices[i])
                }
            }
            else {
                saveAnswers(answers);
                alert("bye!");
                location.href = "http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_26821019.html#a34906406"
            }
        }
        
        function insertNewRowInTable(table, obj) {
            for(var j in obj) break;            
            var row = table.insertRow(table.rows.length);
            var td = row.insertCell(0);
            
            try { rb = document.createElement("<input type=\"radio\" name=\"QA\" />"); } catch(e) { rb = document.createElement("input"); }
            rb.setAttribute("type","radio");
            rb.setAttribute("value",obj[j]);
            rb.setAttribute("name","QA");
            var lb = document.createElement("label");
            lb.innerHTML = j;
            td.appendChild(rb);
            td.appendChild(lb);
        }
        
        function saveAnswer(radio) {
            answers.push(radio.parentElement.getElementsByTagName("label")[0].innerHTML);
        }
        
        function saveAnswers(myArray) {
            // ajax operation to save the array in the database
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <h1 id="question"></h1>
    <table id="choices"></table>
    <br />
    <input type="button" value="Next" onclick="nextQA();" />
    </form>
</body>
</html>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34908878
Assuming our quiet asker use ASP
0
 
LVL 82

Expert Comment

by:leakim971
ID: 34908975
eh eh @mplungjan
I checked its other posts before ;-) and we can remove the first line and  runat="server" lines 4 and 62, no problem
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34909064
'k...
0
 

Author Closing Comment

by:anshealth
ID: 34909210
thx
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question