Jquery表单验证不起作用,没有使用插件

时间:2013-09-19 17:01:03

标签: javascript jquery validation

我是Jquery的新手并遇到了一些我无法解决的事情,认为我需要一个有更多经验的人。

表单验证无法正常工作,但在jsfiddle上运行正常。

我想要有document.ready吗?

任何帮助都会非常感谢

      <script>

  $('#add_film').submit(function (e) {

var error = false;

// No value for movie_title
if ($('#movie_title').val() == "") {
    alert("No Film");
    error = true;
}

// No Value for actor
if ($('#leading_name').val() == "") {
    alert("No actor");
    error = true;
}

// No value for rating
if ($('#rating').val() == null) {
    alert("No Rating");
    error = true;
}

//No value for review
if ($('#review').val() == "") {
    alert("No review");
    error = true;
}

// Focus on first form field.
$("input:text:visible:first").focus();

if (error) {
    e.preventDefault();
}

});

</script>




   <form action="add_film.php" method="post" id="add_film">

    <label for="title">Movie Title</label>
    <input type="text" name="movie_title" id="movie_title" />

    <br/>
    <br/>

    <label for="actor">Leading Actor</label>
    <input type="text" name="leading_actor" id="leading_name" />

    <br/>
    <br/>      


    <label for="rating">Rating</label>
    <select id="rating" name="rating"/>
        <option selected="selected" value=0 disabled="disabled">Select a Rating</option>
        <option value="Terrible">Terrible</option>
        <option value="Fair">Fair</option>
        <option value="Ok">Ok</option>
        <option value="Good">Good</option>
        <option value="Excellent">Excellent</option>
    </select>

    <br/>
    <br/>


    <label for="review">Your Review</label>
    <br/>
    <textarea name="review" id="review" rows="15" cols="60"></textarea>

    <br/>
    <br/>

    <input type="submit" name="submit" id="submit" value="submit" />
    <input type="hidden" name="submitted" value="TRUE" />

3 个答案:

答案 0 :(得分:2)

您尚未关闭表单标记,因此脚本无效。

这是您的工作代码。

http://jsbin.com/EDOJEZ/1/edit?html,output

答案 1 :(得分:0)

是!!!代码应该在文档就绪处理程序

jQuery(function($){

    $('#add_film').submit(function (e) {

        var error = false;

        // No value for movie_title
        if ($('#movie_title').val() == "") {
            alert("No Film");
            error = true;
        }

        // No Value for actor
        if ($('#leading_name').val() == "") {
            alert("No actor");
            error = true;
        }

        // No value for rating
        if ($('#rating').val() == null) {
            alert("No Rating");
            error = true;
        }

        //No value for review
        if ($('#review').val() == "") {
            alert("No review");
            error = true;
        }

        // Focus on first form field.
        $("input:text:visible:first").focus();

        if (error) {
            e.preventDefault();
        }
    });
})

答案 2 :(得分:0)

您可以在google chrome中运行您的网页,然后按ctrl + shift + j打开开发者控制台。这样你就可以在那里看到带有行号+预览的javascript / jquery错误,并尝试自己解决。我保证,你可以这么简单。

相关问题