I tried to do an "if/then" statement in javascript but the "then" mand is being ignored. Any ideas on why?
Specifically I want the form to be validated that the two text boxes are not blank and once that is validated I want a DIV ID = section2 to appear.
function checkanswers() {
var fdet = document.wastheform;
if (fdet.question_type[0].checked) {
var elements = new Array("name","address");
var elements_name = new Array("name", "address");
for (var i = 0; i < elements.length; i++) {
if ($("#" + elements[i]).val() == "") {
err = "Please enter " + elements_name[i] + "";
alert(err);
return false;
}
}
$("#section2").show();
}
I tried to do an "if/then" statement in javascript but the "then" mand is being ignored. Any ideas on why?
Specifically I want the form to be validated that the two text boxes are not blank and once that is validated I want a DIV ID = section2 to appear.
function checkanswers() {
var fdet = document.wastheform;
if (fdet.question_type[0].checked) {
var elements = new Array("name","address");
var elements_name = new Array("name", "address");
for (var i = 0; i < elements.length; i++) {
if ($("#" + elements[i]).val() == "") {
err = "Please enter " + elements_name[i] + "";
alert(err);
return false;
}
}
$("#section2").show();
}
if
here. Which one doesn't seem to work ? And how did you chek it ?
– Denys Séguret
Commented
Feb 21, 2013 at 16:01
I'm assuming your "then" is the showing of the div. In which case I would do something like this:
function checkanswers() {
var fdet = document.wastheform;
if (fdet.question_type[0].checked) {
if(withoutValue("#name")) {
alert("Please enter name")
}
else if(withoutValue("#address")) {
alert("Please enter address")
} else {
$("#section2").show();
}
}
}
function withoutValue(selector) {
return $(selector).val() === "";
}
Is that what you're looking for?
Your question implies that you want an if/then behavior (in Javascript, this is more properly referred to as an if/else statement), but the way you structured your code, there is no "then". Here is how the if statement should work:
if ( condition )
{
// do something if the condition is true
}
else
{
// do something if the condition is false
}