Javascript不是';t被HTML中的提交按钮调用


Javascript isn't being called by submit button in HTML

由于某些原因,当按下提交按钮时,我的javascript不会执行。如果用户名和电子邮件地址为空,它应该在两个文本字段旁边留下一条错误消息,但事实并非如此,我也不知道为什么。通常,当这两个框被填满时,提交会转到一个php页面,该页面会发送一封电子邮件。任何关于解决我的javascript问题的建议或帮助都将不胜感激。

这是我的javascript:

//my javascript function
<script type='text/javascript'>
function validate_form()
{
        $('span.error_message').html('');
        var success = true;
        $("#validate_form input").each(function()
        {
            if($(this).val()=="")
            {
                $(this).next().html("* You must complete this field"); // the error message
                success = false;
            }
        });
        return success;
    }
</script>

以及我在html:中的表单

<form action=".....whatever....." method="POST" id="validate_form" onsubmit="return validate_form();">
    <ol>
        <li>
            <span id="question">___ is your name? My name is Marie.</span>
            <input type="text" name="q1" id="q1" />
        </li>
        <li>
            <span id="question">___ are you from? I'm from Paris, France.</span>
            <input type="text" name="q2" id="q2" />
        </li>
        <li>
            <span id="question">Dave: ___ you like football</span>
            <p>
                <input type="radio" name="q6" value="1" id="q6_1" />
                <label for="q6_1">Are</label>
                <input type="radio" name="q6" value="2" id="q6_2" />
                <label for="q6_2">Do</label>
                <input type="radio" name="q6" value="3" id="q6_3" />
                <label for="q6_3">Does</label>
                <input type="radio" name="q6" value="4" id="q6_4" />
                <label for="q6_4">Is</label>
            </p>
        </li>
    <div id="username">
        <p>
            Before we begin, please enter your name and email:
            <br />
            <label for="user_name">Name: </label><input type="text" name="user_name" id="user_name" />
                <span class="error_message" style="color:#FF0000"></span>
            <br />
            <label for="user_email">Email: </label><input type="text" name="user_email" id="user_email" />
                <span class="error_message" style="color:#FF0000"></span>
        </p>
    </div>
        <p style="width: 242px; margin: auto;">
            &nbsp;
            <input type="submit" name="submit" value="Submit your answers" id="but" />
        </p>
</form>

编辑:修复了调用javascript的问题,但现在即使填充了两个文本字段,提交按钮也无法工作。

$("#validate_form input")-我在任何地方都看不到validate_form;您需要添加它,或者只使用:$("input")

firefox的Firebug将帮助您调试这些类型的jscript问题。如果你不想安装firebug,你也可以使用Firefox中的错误控制台。