0

我正在用花哨的盒子构建一个表单,表单工作正常,但我无法从文本框中获得价值。

我的java脚本是

$(function () {
    $("#button").click(function () {
        var yourName = $("input#yourName").val();
        alert(yourName);
        if (yourName == "") {
            $('input#yourName').css({
                backgroundColor: "#F90"
            });
            $("input#yourName").focus();
            return false;
        }

        $.ajax({
            type: "POST",
            url: "bin/form1.php",
            data: $("#login_form").serialize(),
            context: document.body,
            success: function (res) {
                var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
                success = success.replace(/^\s*|\s*$/g, "");
                var RegularExpression = new RegExp(success);

                if (RegularExpression.test(res)) {
                    alert('Message Sent');
                    $.fancybox.close();
                } else {
                    alert('Error While processing');
                }
            },
        });
        return false;
    });
});

现在我的html是

<div style="display:none; height:450px">
    <form id="login_form" action="">
        <p id="login_error">
            Please, enter data
        </p>
        <input type="hidden" name="action" value="send_friend_post" />
        <label for="yourName" style="margin-right:110px;">
            <?php _e( 'Your name', 'newcorp') ; ?>
        </label>
        <input id="yourName" type="text" name="yourName" value="" class="text_new " />
        <br/>
        <input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
    </form>
</div>

我正在打开这个花哨的弹出框

<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>

一切正常,但我无法获得yourName即使警报显示为空白的价值。

谢谢

4

4 回答 4

2

而不是这个

var yourName = $("input#yourName").val();

尝试

var yourName = $("input[name='yourName']:text").val();

这将使您的函数读取文本框的值。

于 2012-11-09T12:19:14.987 回答
1

首先,使用您的表格,最好使用

$(document).on('submit', 'form', function () { ... })

代替

$(document).on('click', '#myButton', function () { ... })

其次,您应该将代码封装到$(document).ready(function () { .. });

这是一个工作示例;)http://jsfiddle.net/aANmv/1/

于 2012-06-19T11:02:46.157 回答
0
  1. 在打开弹出窗口时检查您输入的 ID 是否未被 fancybox 更改。
  2. 如果使用 jQuery 1.7 > 或使用 jQuery 1.7 <, 则不要直接追赶click事件。liveon

live

$("#button").live('click', function() { ... });

on

$("#button").on('click', function() { ... });

还尝试在加载 DOM 后加载 javascript:

$(document).ready(function(){
    $("#button").live('click', function() { ... });
    ...
});
于 2012-06-19T10:54:55.363 回答
-2

Instead of that

$(function() {

try

$(document).ready() {

this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.

于 2012-06-19T10:50:25.057 回答