I've got a single checkbox which i'd like the unchecked value to be 0 and the checked value to be 1, but when the post goes through, it always shows as 1 whether the box is checked or not..
Here's the checkbox:
<input name="stock[]" type="checkbox" id="stock[]"> value="1" />
here's what it spits out regardless of whether it's checked or not.. (there are multiple "stock" checkboxes..
[stock] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] =>开发者_高级运维 1
[4] => 1
[5] => 1
)
I can't seem to get it working.. :S Any ideas? :)
It seems like you have a extra > in your Checkbox HTML. Value is not used in case of checkboxes.
<input name="stock[]" type="checkbox" />
because you have value="1"
, the form will always submit the value regardless of whether checked or not. So remove the value attribute will help.
And to preset the checkbox to be checked, use the checked
attribute instead. Example:
<input name="stock[]" type="checkbox" checked="checked" />
(Obviously, you need to start by removing that extraneous > sign.)
Checkboxes and radio buttons must have a value attribute. If they're checked, that value is sent when the form is submitted; if they're not checked, no value is submitted. Thus, you can't directly do the "0 if unchecked, 1 if checked" thing. What you can do instead is use the value attribute to detect which checkboxes were checked.
<input type="checkbox" name="stock[]" value="1" id="stock1" />
<input type="checkbox" name="stock[]" value="2" id="stock2" />
<input type="checkbox" name="stock[]" value="3" id="stock3" />
If the 1st and 3rd boxes are checked, but the 2nd is not, then when you look at the value of the stock[] array in your code, you'll find that it contains 1 and 3, but not 2.
Edit: I just confirmed that the reason it looked like all of your checkboxes had values submitted was that you failed to give the form any way to differentiate among them. If you have multiple checkboxes with not only the same name but the same value, then your form results will look something like "stock[] = 1, stock[] = 1, stock[] = 1". PHP will then interpret this as stock[1] = 1, stock[2] = 1, etc., but the point is that stock[2] might actually be the fourth checkbox - neither the form nor php has any way to tell where each value came from.
So bottomline is, you can either use the same name for a series of checkboxes, OR you can use the same value, but not both at once: if you use the same name, you have to use the value to differentiate among the controls; and vice versa, if you want to use the same value, you need to use different names.
By the way, if you don't specify the value of a checkbox, then most browsers will supply a default value of their own - for example, IE and Firefox use "on" (or "ON" in some versions). But depending on such defaults is always a bad idea.
I'm not sure you can/should name an input element "stock[]" - try getting rid of the [] and re-test.
精彩评论