表单处理程序不会阻止默认

时间:2014-04-29 16:32:26

标签: javascript jquery forms

我是jQuery的新手。

我正在尝试提交表单,但表单处理程序并未阻止表单提交。

这是我的表格:

<form action = "myForm.php" id="testForm">
        <ul data-role="listview" data-style="inset">
            <li>
                <label>Message: </label>
                <input type="text" name="message"/>
            </li>
            <li>
                <label>From: </label>
                <input type="text" name = "from" />
            </li>
            <li>
                <label>To: </label>
                <input type="text" name = "to" />
            </li>
        </ul>
        <center><input type="submit" /></center>
    </form>

和jQuery(确实出现在表单之后)

<script>
        $( "#testForm" ).submit(function( event ) {
            event.preventDefault();
            var $form = $(this), 
            messageValue = $form.find("input[name = "message"]").val(),
            messageFrom = $form.find("input[name = "from"]").val(),
            messageTo = $form.find("input[name = "to"]").val(),
            url = "myForm.php";
            var posting = $.post(url, {message: messageValue, from: messageFrom, to: messageTo})
            posting.done(function( data ) {
                var content = $( data ).find( "#content" );
                $( "#result" ).empty().append( content );
            });
        });
    </script>

但表单处理程序不会阻止默认提交。非常感谢任何有关我做错的帮助。

1 个答案:

答案 0 :(得分:1)

您还必须小心选择器中的单引号和双引号

<script type="text/javascript">
$(document).ready(function(){
       $( "#testForm" ).submit(function( event ) {
            event.preventDefault();
            var $form = $(this), 
            messageValue = $form.find("input[name = 'message']").val(),
            messageFrom = $form.find("input[name = 'from']").val(),
            messageTo = $form.find("input[name = 'to']").val(),
            url = "myForm.php";
            var posting = $.post(url, {message: messageValue, from: messageFrom, to: messageTo})
            posting.done(function( data ) {
                var content = $( data ).find( "#content" );
                $( "#result" ).empty().append( content );
            });
        });

})
</script>

        messageValue = $form.find("input[name = 'message']").val(),//correct
        messageValue = $form.find('input[name = "message"]').val(),//correct
        messageValue = $form.find('input[name = 'message']').val()//no
        messageValue = $form.find("input[name = "message"]").val()//no