简体   繁体   中英

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.

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.

Deleting objects from the database is in the db model documentation.

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. See "A Simple Form-Handling Example" on this page Tutorial for form submissions in Django. [/Edit]

Here's an example you can copy into a .html file on your computer and open in a web browser. It's using simple JavaScript. For something like this, I prefer to use jQuery , but depending on your use, it may be more overhead than you prefer. However, if you need to do a multitude of client-side programming, I highly recommend using 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.

Preferably, I'd assign Id's to the table's rows that correlate with each checkbox so they're easier to access.

I also included a <input type="button"> because it was asked for in the original post. 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. 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. 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.

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.

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'].

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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