Fastest way to handle a submit button with a variable in it?
I've got a form with a bunch of items. Beside each item is a "Remove" button. When one of buttons is pressed, I need to know whic开发者_StackOverflow社区h one so that I know which item to remove.
The way I have it now, each button is named remove-#
where #
is the index of the item. In order to grab the #
though I have to loop over every POST value, check if the key starts with remove-
and if it does, parse out the integer.
Is there any method that would be faster than O(n)
where n
is the number of post vars?
Not that n
is so large that this would become an expensive operation, but mostly because I'm curious.
Also, before I get any answers that suggest I use JavaScript and put an onclick event on each button to move the index into a separate hidden input.... I'm trying to do this without JavaScript.
An option would be to put each remove button in a separate form, with a hidden value with a constant name and the value indicating which item to remove.
If the POST values are stored in a dict you could turn this around and instead of looking for something that looks like a remove-# you generate all remove-# and try to use them to index the dict. That would limit the search to O(m) where m is the number of elements that can be removed.
This really is the domain of Javascript. However adding onclick isn't a great way to do this. Use HTML5 data attributes and unobtrusive listeners.. For example, in JQuery/HTML5
<input type='button' class='remove-button' name='remove' data-remove-attr='5'>
$('.remove-button').live("click", function() {
alert($(this).attr("data-remove-attr")); // Alerts 5.
});
Despite the data- being an HTML5 thing, it is backwards compatible with old IE, etc as they always allowed arbitrary dom attributes.
Edit: Note this is O(1) if as your action you did $('#remove-'+id).hide();
精彩评论