[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 627
  • Last Modified:

Javascript If Else Statement

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
anshealth
Asked:
anshealth
3 Solutions
 
CCSOFlagCommented:
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
 
Dave BaldwinFixer of ProblemsCommented:
Further info on this page: http://www.w3schools.com/js/js_if_else.asp
0
 
Michel PlungjanIT ExpertCommented:
@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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
ProculopsisCommented:

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
 
Michel PlungjanIT ExpertCommented:
Keen, are we?
0
 
leakim971PluritechnicianCommented:
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
 
leakim971PluritechnicianCommented:
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
 
Michel PlungjanIT ExpertCommented:
Assuming our quiet asker use ASP
0
 
leakim971PluritechnicianCommented:
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
 
Michel PlungjanIT ExpertCommented:
'k...
0
 
anshealthAuthor Commented:
thx
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now