简体   繁体   English

勾选后如何删除复选框?

[英]How to delete a checkbox when it is ticked?

I have a template that displays the list of items. 我有一个显示项目列表的模板。 It has one checkbox to each item. 每个项目都有一个复选框。 I want to be able to remove an item from a checkbox when a checkbox is ticked. 我希望能够在选中复选框时从复选框中删除项目。 So I would need a button that deletes an item once a checkbox is selected. 因此,我需要一个按钮,用于在选中复选框后删除项目。 Here is my template. 这是我的模板。

    {% for item in items %}
         <tr>
         <td><input type="checkbox" name="item" value="{{item.pk}}" checked="checked"></td>
         <td>{{item.tiptop_id}}</td><td>{{item.alternative_id}}</td><td>{{item.title}}</td>
         <td>{{item.type}}</td><td>{{item.format}}</td>
         </tr>
    {% endfor %}

I would need probably know what to write in my views as well I guess. 我猜可能我也需要知道该写些什么。

Edit: 编辑:

Not sure why it is still not deleting. 不知道为什么它仍然没有删除。 check out my views. 查看我的意见。 My edit order form. 我的编辑订单表格。 It is quiet huge. 它是安静的巨大。 I thought the delete function would do the trick. 我认为删除功能可以解决问题。 Anyway take a look. 反正看看。

def edit_order(request, order_no):
# Alot of code here
     if request.method == 'POST':
            form = forms.OrderForm(request.POST, instance = order)
            if form.is_valid() and save_item is not None:
                form.save(True)
                request.user.message_set.create(message = "The order has been updated successfully.")
                return HttpResponse("<script language=\"javascript\" type=\"text/javascript\">window.opener.location = window.opener.location; window.close();</script>")

        if status is not None and contact is not None and save_status is not None and delete_item is not None:
            try:
                for id in status_items:
                    item = models.StorageItem.objects.get(pk = id)
                    delete_item = item
                    delete_item.delete()
                    current_status = models.ItemStatusHistory(item = item, contact = contact, status = status,
                                                    user = request.user)
                    current_status.save()
            except:
                pass
            request.user.message_set.create(message = "Status successfully changed for {0} items".format(len(status_items)))

You need to write a view that gets the POST data, finds out which checkboxes have been checked, and then deletes the items from the database matched by id. 您需要编写一个获取POST数据的视图,找出已选中哪些复选框,然后从数据库中删除ID匹配的项目。

You probably also want to wrap the view in a decorator to make sure the user has permission to delete things, or check the logged-in user is the same as the owner of the item to be deleted, if that's how you want to do thing. 您可能还希望将视图包装在装饰器中,以确保用户有权删除内容,或者如果要这样做,请检查登录用户是否与要删除的项目的所有者相同。 。

Or you could use Django's forms framework to handle some of the heavy work. 或者,您可以使用Django的表单框架来处理一些繁重的工作。

Deleting objects from the database is in the db model documentation. 从数据库中删除对象在db模型文档中。

These things aren't totally trivial so don't wait too long here for a full solution - get hacking! 这些事情并不完全是琐碎的,所以不要在这里等待太长时间以寻求完整的解决方案-进行黑客攻击!

[Edit]: The real issue is being able to delete items from a database on a form submission, not removing rows from a HTML table. [编辑]:真正的问题是能够从表单提交数据库中删除项目,而不是从HTML表中删除行。 See "A Simple Form-Handling Example" on this page Tutorial for form submissions in Django. 有关在Django中提交表单的信息,请参见此页面教程上的“一个简单的表单处理示例” [/Edit] [/编辑]

Here's an example you can copy into a .html file on your computer and open in a web browser. 您可以将以下示例复制到计算机上的.html文件中,然后在网络浏览器中打开。 It's using simple JavaScript. 它使用简单的JavaScript。 For something like this, I prefer to use jQuery , but depending on your use, it may be more overhead than you prefer. 对于这样的事情,我更喜欢使用jQuery ,但是根据您的使用情况,它可能会比您喜欢的开销更大。 However, if you need to do a multitude of client-side programming, I highly recommend using jQuery. 但是,如果您需要进行大量的客户端编程,我强烈建议您使用jQuery。

Note: I think it's a little messy using parentNode.parentNode.parentNode, but this example purposely uses a table/checkbox configuration as expressed in the original post. 注意:我认为使用parentNode.parentNode.parentNode有点混乱,但是此示例故意使用表/复选框配置,如原始文章中所述。

Preferably, I'd assign Id's to the table's rows that correlate with each checkbox so they're easier to access. 最好将ID分配给与每个复选框相关的表的行,以便更易于访问。

I also included a <input type="button"> because it was asked for in the original post. 我还包括了<input type="button">因为它是原始帖子中所要求的。 You may want to consider assigning the onclick= event to each checkbox so the user can remove the items as soon as they're clicked. 您可能需要考虑将onclick=事件分配给每个复选框,以便用户可以在单击项目后立即将其删除。 But that's a preference. 但这是一种偏爱。

<html>
<head>
<script>

function hideCheckedRows() {
    var checkboxes = document.getElementsByName("item");
    var checkboxes_to_remove = new Array();
    var count = 0;
    for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].checked == true) {
            checkboxes_to_remove[count++] = checkboxes[i];
        }
    }
    for (var i = 0; i < checkboxes_to_remove.length; i++) {
        cbx = checkboxes_to_remove[i];
        // parentNode.parentNode.parentNode is the <tr>
        // parentNode.parentNode is the <td> containing the checkbox
        cbx.parentNode.parentNode.parentNode.removeChild(
                                          cbx.parentNode.parentNode);
    }
}
</script>
</head>
<body>

<table>
    <tr name="table_row">
        <td><input type="checkbox" name="item" value="Check1"></td>
        <td>Id1</td><td>Alt_Id1</td><td>Title1</td>
          <td>Type1</td><td>Format1</td>
    </tr>
    <tr name="table_row">
        <td><input type="checkbox" name="item" value="Check2"></td>
        <td>Id2</td><td>Alt_Id2</td><td>Title2</td>
          <td>Type2</td><td>Format2</td>
    </tr>
    <tr name="table_row">
        <td><input type="checkbox" name="item" value="Check3"></td>
        <td>Id3</td><td>Alt_Id3</td><td>Title3</td>
          <td>Type3</td><td>Format3</td>
    </tr>
</table>

<input type="button" value="Click to remove checkboxes!" 
       onclick="hideCheckedRows();"/>

</body>
</html>

Edit: 编辑:

If you want the item deleted from the database, we need more information. 如果您希望从数据库中删除该项目,我们需要更多信息。 We need to know what kind of database being used and what the server-side code that handles the submit button's "POST" looks like. 我们需要知道正在使用哪种数据库,以及处理提交按钮的“ POST”的服务器端代码是什么样的。 This example will delete the checkbox from the table in the user's web browser, but it will have no effect on whatever on the database. 本示例将从用户的Web浏览器中的表中删除该复选框,但对数据库上的任何内容均无效。

You're doing it wrong :) Create a view only for deleting. 您做错了:)创建仅用于删除的视图。 Send in POST or GET id of the element (or in url), remove the element from db and then as response send your list without the deleted element. 发送该元素的POST或GET ID(或url),从db中删除该元素,然后作为响应发送未删除元素的列表。

Something like this : 像这样的东西:

def delete_element(request, id): 
    el = get_object_or_404(Element, id=id)

    if el:
        el.delete()

    html = render_list(request)

    if request.is_ajax():
        result = simplejson.dumps({
            "html": "html",
        }, cls=LazyEncoder)
        return HttpResponse(result, mimetype='application/javascript') 

def render_list(request):
    elements = Element.objects.all()
    return render_to_string(template_name, RequestContext(request, {
        "element" : elements, })

And then in your template you first call url of delete function with javascript and then on success you update your template with data['html']. 然后,在模板中,您首先使用javascript调用delete函数的url,然后在成功时,使用data ['html']更新模板。

You can ask this guy : http://twitter.com/sasklacz as he's writing some tutorials on ajax in django to give you the exact code needed. 您可以问这个人: http : //twitter.com/sasklacz,因为他正在django上用ajax编写一些教程,以为您提供所需的确切代码。

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

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