动态生成表单并使用.live()时如何获取表单输入的属性

发布于 2024-09-16 15:05:08 字数 3144 浏览 2 评论 0原文

我正在从使用 getJSON 获取的 JSON 对象动态创建表单。如果有更好的方式以这种方式构建表单,请告诉我。我用这个例子来了解如何重新绑定提交按钮: 在 jQuery ajax 响应后重新绑定动态创建的表单**

我要做什么需要知道的是如何获取我单击的输入提交按钮的类。有一个“批准”和“拒绝”按钮,根据单击的按钮将在 POST 中发送到服务器,因此我知道如何处理在服务器端 POST 的表单数据。

这是代码:

<script type="text/javascript">
$().ready(function(){
    jQuery("form[id^='message-']").live('submit', function(){

        var id = parseInt(this.id.replace("message-", ""));

        // this is not the value of the class attribute from submit button clicked.      
        var action = this.attr('class');
        alert(action);

        return false;

        jQuery.ajax({
            type: "POST",
            url: "/path/to/ajaxhandler.php",
            data: {"action": action, "id": id},
            success: function(response) {                
        }           
    });

    /*
        generate form
    */
    $.fn.getAllUnapprovedMessages = function () {
        $.getJSON("/messages.php?a=getAllUnapproved, function(data){
            var i=0;
            $("div#messages").empty();

            while(i<data.length) {
                $('div#messages').append(
                    '<div id="msg-'+data[i].id+'" style="border: 1px coral solid; margin: 5px 5px 5px 5px;">'+
                    '<form id="message-'+data[i].id+'" name="form-'+data[i].id+'" action="/path/to/ajaxhandler.php" >'+
                    'From: '+data[i].u_from+' ----> To: '+data[i].u_to+'<br />'+
                    'Subject: <br /><input name="subject" type="text" value="'+data[i].subject+'" /> <br /><br />'+
                    'Message: <br /><textarea rows="10" cols="60">'+data[i].text+'</textarea><br />'+
                    '<input class="formApprove" type="submit" id="approve-'+data[i].id+'" value="Approve" /> or '+
                    '<input class="formDeny" type="submit" id="deny-'+data[i].id+'" value="Deny" />'+
                    '</form></div>');
                i++;
            }
        });
    }
}
</script>

这是我需要更改才能正确的内容:

// this is not the value of the class attribute from submit button clicked.      
var action = this.attr('class');
alert(action);

这样我就可以从单击的按钮获取类属性。

更新(2010 年 8 月 27 日)- 这是我为任何偶然发现此问题并需要答案的人所做的事情:

对于 serializeObject() 函数,请参阅这篇文章: 使用 jQuery 将表单数据转换为 JavaScript 对象

$(".formApprove").live('click', function() {
    var fid = this.id.replace(/approve-/i, "");
    var formObject = $('form#message-'+fid).serializeObject();

    $.post('/path/to/ajaxhandler.php', {
        a: 'setApproved',
        id: fid,
        subject: formObject.subject,
        message: formObject.message
    }, function(res) {
        if(res.result == 0) {
            alert ('done');
        } else {
            alert ('Error');
    },"json");
    return false;
});

I am dynamically creating forms from a JSON object that I fetch with a getJSON. If there is a better way of building forms in this manner, please let me know. I used this example to understand how to rebind submit button:
Rebind dymanically created forms after jQuery ajax response**

What I need to know is how to grab the class of the input submit button I have clicked. There's an "Approve" and "Deny" button and depending on which one is clicked will be sent to the server in a POST so I know what to do with the form data being POST'ed on the server side.

Here's the code:

<script type="text/javascript">
$().ready(function(){
    jQuery("form[id^='message-']").live('submit', function(){

        var id = parseInt(this.id.replace("message-", ""));

        // this is not the value of the class attribute from submit button clicked.      
        var action = this.attr('class');
        alert(action);

        return false;

        jQuery.ajax({
            type: "POST",
            url: "/path/to/ajaxhandler.php",
            data: {"action": action, "id": id},
            success: function(response) {                
        }           
    });

    /*
        generate form
    */
    $.fn.getAllUnapprovedMessages = function () {
        $.getJSON("/messages.php?a=getAllUnapproved, function(data){
            var i=0;
            $("div#messages").empty();

            while(i<data.length) {
                $('div#messages').append(
                    '<div id="msg-'+data[i].id+'" style="border: 1px coral solid; margin: 5px 5px 5px 5px;">'+
                    '<form id="message-'+data[i].id+'" name="form-'+data[i].id+'" action="/path/to/ajaxhandler.php" >'+
                    'From: '+data[i].u_from+' ----> To: '+data[i].u_to+'<br />'+
                    'Subject: <br /><input name="subject" type="text" value="'+data[i].subject+'" /> <br /><br />'+
                    'Message: <br /><textarea rows="10" cols="60">'+data[i].text+'</textarea><br />'+
                    '<input class="formApprove" type="submit" id="approve-'+data[i].id+'" value="Approve" /> or '+
                    '<input class="formDeny" type="submit" id="deny-'+data[i].id+'" value="Deny" />'+
                    '</form></div>');
                i++;
            }
        });
    }
}
</script>

Here is what I need to change to be correct:

// this is not the value of the class attribute from submit button clicked.      
var action = this.attr('class');
alert(action);

So I can get the class attribute from the button that was clicked.

UPDATE (8.27.2010) - Here's what I did for anyone who stumbles across this and needs an answer:

For the serializeObject() function, see this post: Convert form data to JavaScript object with jQuery

$(".formApprove").live('click', function() {
    var fid = this.id.replace(/approve-/i, "");
    var formObject = $('form#message-'+fid).serializeObject();

    $.post('/path/to/ajaxhandler.php', {
        a: 'setApproved',
        id: fid,
        subject: formObject.subject,
        message: formObject.message
    }, function(res) {
        if(res.result == 0) {
            alert ('done');
        } else {
            alert ('Error');
    },"json");
    return false;
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

金兰素衣 2024-09-23 15:05:08

简短的回答是,你不能。您无法仅从表单的提交事件获取对导致表单提交的元素的引用。您还需要将处理程序连接到按钮的单击事件。如果您为输入标签指定 name 属性,则在正常的完整发布过程中,它们的值将与其余表单值一起发送到服务器,但当您想通过 Ajax 执行此操作时,这并没有多大帮助。

我建议您修改代码来处理按钮的单击事件,并在该处理程序中收获类/值属性,然后触发表单的提交事件并将属性值作为自定义事件数据传递,然后您可以从表单提交处理程序。如果传递的数据为空/未定义。

Short answer is, you can't. You can't get a reference to the element that caused the form to submit from the form's submit event alone. You'll need to wire up handlers to the buttons' click events too. If you give the input tags a name attribute, their value will be sent to the server with the rest of the form values during a normal, full post, but that doesn't help much when you want to do it via Ajax.

I'd suggest you modify the code to handle the buttons' click events and in that handler harvest the class/value attribute, then trigger the form's submit event and pass the attribute value in as custom event data, which you can then read from the form submit handler. If the passed data is null/undefined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文