示例HTML + JS表单不起作用

时间:2013-05-29 14:31:45

标签: javascript html

这是我第一次尝试使用Javascript,但大约两个小时之后,我无法弄清楚我正在犯的错误。我确定它很小,但我无法弄清楚为什么它在JSFiddle中不起作用。

这是HTML:

<form name="myForm" onsubmit="return validateForm()" method="post">
<!--Question Block One-->
Do you have a name?
<br>
Yes<input type="radio" name="first" value="yes"> 
No<input type="radio" name="first" value="no">
<br>
<input type="submit" value="Submit">
</form>

这是JS:

function validateForm()
{
var x=document.forms["myForm"]["first"].value;
if (x==null || x=="")
  {
  alert("Please answer the first question!");
  return false;
  }
 else if (x=="yes")
 {
   alert("Thanks");

 }
    else if (x=="no"
 {
  alert("Sorry, we can't help");
 }
}

错误:

{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x9b6da8c>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x98e9c0c>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x9b6da8c>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x9ccfe4c>, 'help_text': '', 'name': 'js_wrap'}"}

这是JS小提琴:http://jsfiddle.net/4WesX/

1 个答案:

答案 0 :(得分:3)

您错过了else if个语句的结束括号,请参阅此处:

else if (x=="no"

编辑:实际上,这不仅仅是一个问题。

您没有正确查询这些单选按钮的值。首先,给他们ID:

Yes<input type="radio" id="yes" name="first" value="yes"> 
No<input type="radio" id="no" name="first" value="no">

然后你可以这样做:

function validateForm()
{
    var yes = document.getElementById("yes");
    var no = document.getElementById("no");

    if (!yes.checked && !no.checked)
    {
        alert("Please answer the first question!");
        return false;
    }
    else if (yes.checked)
    {
        alert("Thanks");
    }
    else if (no.checked)
    {
        alert("Sorry, we can't help");
    }
}

Fiddle