简体   繁体   English

提交AjaxForm时确定一个特定的按钮

[英]Identifying a Specific Button when Submitting AjaxForm(s)

I'm using Django and AjaxForm to submit a form(s) that adds an item to a user's "cart". 我正在使用Django和AjaxForm提交一个将项目添加到用户“购物车”的表单。 I have multiple items listed on the page, each with it's own "add to cart" button. 我在页面上列出了多个项目,每个项目都有自己的“添加到购物车”按钮。 Upon clicking a specific "add to cart" button, I use Ajax to add the item to the user's "cart" and display it in their "cart" at the top of the screen. 单击特定的“添加到购物车”按钮后,我使用Ajax将商品添加到用户的“购物车”中,并在屏幕顶​​部的用户的“购物车”中显示该商品。 Users can also delete an item from their cart by clicking on a given item in the cart. 用户还可以通过单击购物车中的给定项目从购物车中删除项目。

I would now like to change the appearance of the "add to cart" button once it has been clicked, but I am having trouble identifying only the specific button that was clicked (and not all of the 'add to cart' buttons). 现在,我想更改“添加到购物车”按钮的外观,但是我很难识别仅被单击的特定按钮(而不是所有“添加到购物车”按钮)。 How can I identify which 'add to cart' button was clicked. 如何确定单击了哪个“添加到购物车”按钮。 I added an 'id' field to my html button and have been trying to use that but have been unsuccessful....?? 我在我的html按钮中添加了一个“ id”字段,并一直尝试使用该字段,但操作失败。

I have tried many different things but either they are not working or I am putting them in the wrong spot. 我尝试了许多不同的方法,但是要么它们无法正常工作,要么我将它们放在错误的位置。 For example, I have tried: 例如,我尝试过:

$('.add-to-cart').on('click',function(){
    var id = $(this).attr("id");
    console.log("ID: ");
    console.log(id);
});

And also: 并且:

var addButtonID;
    $(this).find('input[type=submit]').click(function() {
        addButtonId = this.id;
        console.log("ID: ");
        console.log(addButtonId)
    )};

Any ideas on how I can find the specifc button that was clicked so I can update the button's appearance??? 关于如何找到单击的特定按钮的任何想法,以便我可以更新按钮的外观???

My html: 我的html:

{% for item in item_list %}             
    <form class="add-to-cart" action="/item/add/{{ item.id }}/" method="post" enctype="application/x-www-form-urlencoded">
    <ul>
        <li style="display: block"><button class="addItemButton2" type="submit" id="{{ item.id }}">Add to Cart</button></li>
    </ul>
    </form>
{% endfor %}

My javascript: 我的JavaScript:

function remove_form_errors() {
    $('.errorlist').remove();
}
function show_hide_cart(){
    var cart = $('#cart');
    var message = $('#message');
    if (cart.find('li').length >= 1){
        cart.show();
        continueButton.show();
        message.hide();
    }
    else {
        cart.hide();
        continueButton.hide();
        message.show();
    }
}

function process_form_errors(json, form)
{
    remove_form_errors();

    var prefix = form.data('prefix'),
    errors = json.errors;
    if (errors.__all__ !== undefined) {
        form.append(errors.__all__);
    }
    prefix === undefined ? prefix = '' : prefix += '-';
    for (field in errors)
    {
        $('#id_' + prefix + field).after(errors[field])
        .parents('.control-group:first').addClass('error');
    }
}
function assign_remove_from_cart() {
    var cart = $('#cart');
    $('.remove-from-cart').on('click', function(e) {
        e.preventDefault();
        $.get(this.href, function(json) {
            remove_form_errors();
            cart.find('a[href$="' + json.slug + '/"]').parent('li').remove();
            show_hide_cart();
        });
    });
}
(function($){
    $(function() {
        var cart = $('#cart'),
            message = $('#message');
            continueButton = $('#continueButton');  

        assign_remove_from_cart();
        // ajax-enable the "add to cart" form
        $('.add-to-cart').ajaxForm({
            dataType: 'json',
            url: this.action,
            success: function(json, status, xhr, form) {
                if (json.errors !== undefined) {
                    // display error message(s)
                    process_form_errors(json, form);
                }
                else if(json.id == -1){
                    // duplicate, do nothing
                    console.log("json.id:%s:json.slug:%s", json.id, json.slug)
                }
                else {
                    // Hide any previously displayed errors
                    remove_form_errors();
                    // compile cart item template and append to cart
                    var t = _.template($('#cart-item-template').html());
                    $('#cart').append(t(json));
                    show_hide_cart();
                    assign_remove_from_cart();
                }
            }
        });
    });
})(jQuery);

Change the button type to 'button', and then add onClick="addToCartFunction(this);" 将按钮类型更改为“按钮”,然后添加onClick =“ addToCartFunction(this);”

then in the addToCarFunction, this.id will be your item id your adding?, or you can use data-attributes to add more item details for the function to get. 然后在addToCarFunction中,this.id将是您添加的商品ID ?,或者您可以使用data-attributes添加更多商品详细信息以获取该函数。

if you then need to send information to the server to cache the cart, use a $.ajax jQuery call to the server. 如果您随后需要将信息发送到服务器以缓存购物车,请使用对服务器的$ .ajax jQuery调用。

Based on your comments, you ought to be able to drop your onClick function into a script tag at the end of your HTML page and have it function as intended (though your javascript should actually all be in a separate file that gets referenced via a script tag). 根据您的评论,您应该能够将onClick函数放到HTML页面末尾的script标记中,并使其按预期运行(尽管您的javascript实际上应该都位于通过脚本引用的单独文件中)标签)。

$( document ).ready(function(){ 
    $('.add-to-cart :submit').on('click',function(){ 
        var id = this.id; 
        console.log("ID: ",id); 
        //do something with your ID here, such as calling a method to restyle your button
        $('#' + id).css("attribute","new value");
        //or
        $('#' + id).addClass("yourClassName");
    }); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM