开发者

Unchecked checkboxes and hidden input problem

开发者 https://www.devze.com 2023-01-26 16:51 出处:网络
We have an edit form:we populate it with a variable number of checkboxes (it all depends,let\'s say, on how many pictures we have on the article we\'re about to edit).

We have an edit form:we populate it with a variable number of checkboxes (it all depends,let's say, on how many pictures we have on the article we're about to edit).

All the checkboxes are per default "checked" and if nothing happens the data associated(our pictures in this case) remains untouched.

Altough if we uncheck one we actually want to not keep the picture in our edited post and delete it from our database.

I know unchecked checkboxes dont get Posted,and that I have one work-around:

place right before the checkbox an hidden field with the same name..in this way with the checkbox unchecked can still post the hidden input.

but i have this situation:

/*i'm querying the database to load all the article's data and I check if  */
/* there's any picture so I build, with a while loop, an associated checkbox*/
 <input type="checkbox" name="picture[]" value="$row['pic_id]"/>$row['pic_name'] 

When I submit our edit form I check if there's any data inside our array picture and if positive i want to delete it from database. Now if I simply add an hidden field at the top of each checkbox (so same name and same value..cause it's the value i need to use in the 开发者_C百科next query) I fall into the problem:

how to distinguish if the posted data comes from the actual checkbox (if eventually checked) or from the hidden input??

thanks again Luca


Why don't you check it on the server side?

You know what was the original list, you have your new list. Those that are not in the new list, but were in the original list, should be deleted.

So you don't need to add any javascript hacks, or hidden inputs.


On the server side you can use the following approach:

$array_of_ids_to_delete=array_diff($array_with_all_ids, $posted_ids);

The $array_with_all_ids must be already available, because I guess you use it to output all the checkboxes. $posted_ids represents your picture[] array.

After that you only have to run a foreach on $array_of_ids_to_delete and get rid of those images.

0

精彩评论

暂无评论...
验证码 换一张
取 消