Do checkbox inputs only post data if they're checked?
Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.
The default value is always "on", this should be consistent across browsers.
This is covered in the W3C HTML 4 recommendation:
Checkboxes (and radio buttons) are on/off switches that may be toggled
by the user. A switch is "on" when the control element's checked
attribute is set. When a form is submitted, only "on" checkbox
controls can become successful.
Post only checked values input type='checkbox' name='Product.Categories[i].Id' value='x' / to viewmodel
You have a hidden input in your foreach loop, it will send all the categories to the post edit. Just remove it:
<input type="hidden" name="Product.Categories[@counter].Id" value="@category.Id" />
Update:
You can use jquery to change the selected checkboxes name when submit the form:
@model EditVM
@{
var categoryIdList = @Model.Product.Categories.Select(x => x.Id); //Again, contains only the categories the Product is bound to (And gets the id's)
int counter = 0;
}
<form asp-action="Edit" method="post">
@foreach (Category category in Model.Categories)//Loop through all the categories in the db
{
if (categoryIdList.Contains(category.Id))
{
<input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" checked />
}
else
{
<input type="checkbox" name="Product.Categories[@counter].Id" value="@category.Id" />
}
<label>@category.Name</label>
{ counter++; }
}
<input id="btn" type="submit" value="submit" />
</form>
@section scripts{
<script>
$("input[type=checkbox]").on("click", function () {
if ($(this).attr('checked')) {
$(this).removeAttr('checked');
} else {
$(this).attr('checked','checked')
}
})
$("#btn").on("click", function () {
var x = 0;
$("input[type = checkbox]").each(function () {
if ($(this).attr('checked')) {
$(this).attr('name', "Product.Categories[" + x + "].Id")
x++;
}
})
})
</script>
}
POST unchecked HTML checkboxes
Add a hidden input for the checkbox with a different ID:
<input id='testName' type='checkbox' value='Yes' name='testName'>
<input id='testNameHidden' type='hidden' value='No' name='testName'>
Before submitting the form, disable the hidden input based on the checked condition:
form.addEventListener('submit', () => {
if(document.getElementById("testName").checked) {
document.getElementById('testNameHidden').disabled = true;
}
}
Sending POST with checkbox value changes with Django
Thank you for your guidance ger.s.brett. I used the answer to this post
to solve my problem.
This looks to see if the field is in the POST:
reviewed = request.POST.get('reviewed', "false")
If the field is present then it uses the POST value. If it is not present it sees it as false.
How to submit 0 if checkbox is unchecked and submit 1 if checkbox is checked in HTML
Simplest one, no javascript required, just put a hidden input before the checkbox:
<input type="hidden" name="check[0]" value="0" />
<input type="checkbox" name="check[0]" value="1" />
Inputs need to have the same name. If the checkbox is checked then value 1 will be submitted, otherwise value 0 from the hidden input.
Your case javascript solution, no hidden inputs needed:
<script type="text/javascript">
// when page is ready
$(document).ready(function() {
// on form submit
$("#form").on('submit', function() {
// to each unchecked checkbox
$(this + 'input[type=checkbox]:not(:checked)').each(function () {
// set value 0 and check it
$(this).attr('checked', true).val(0);
});
})
})
</script>
<form method="post" id="form">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
PHP solution, no hidden inputs needed:
<?php
// if data is posted, set value to 1, else to 0
$check_0 = isset($_POST['check'][0]) ? 1 : 0;
$check_1 = isset($_POST['check'][1]) ? 1 : 0;
?>
<form method="post">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
EDIT: the javascript solution is not valid anymore as of jquery 1.6. Based on this, a more proper solution is the following:
<script type="text/javascript">
// when page is ready
$(document).ready(function() {
// on form submit
$("#form").on('submit', function() {
// to each unchecked checkbox
$(this).find('input[type=checkbox]:not(:checked)').prop('checked', true).val(0);
})
})
</script>
<form method="post" id="form">
<input type="checkbox" name="check[0]" value="1" />
<input type="checkbox" name="check[1]" value="1" />
<input type="submit" value="Save Changes" />
</form>
How to send all checkboxes whether checked or unchecked on form submit?
This is how PHP handles multiple values for parameters ending in []. If you want to overwrite the 0 value with a checked checkbox, you will need to explicitly name the index, otherwise PHP interprets it as values that should be appended to the array.
So, use either grouped_checkbox
or grouped_checkbox[0]
.
Like this:
<input name="grouped_checkbox[0]" type="hidden" value="0">
<input name="grouped_checkbox[0]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->
<input name="grouped_checkbox[1]" type="hidden" value="0">
<input name="grouped_checkbox[1]" type="checkbox" value="1"> <!-- this will overwrite the previous one, if checked -->
<!-- ... and so forth -->
HTML Input Checkbox return 'On' instead of 'True' when submitting form
Set the checkboxes value
attribute to true
and you will get true
in your post value.
Retrieve Checked Checkboxes with PHP and post
The first issue I see from looking at your code is your use of the equality operator (==
) instead of the assignment operator (=
) when setting your variables.
This:
$edges == 'yes';
Should be:
$edges = 'yes';
It's hard to tell from your question whether your issue simply comes down to this.
You state you're using that code for each of your checkboxes. All of your checkbox conditions can go inside the single submit isset()
block.
E.g.
if ( isset( $_POST['submit'] ) ) {
// test for edges...
// test for light...
}
Given your markup, you should be using isset()
for the checkboxes. If you post the form and those checkboxes aren't checked, they won't be set in $_POST
.
Complete example:
if ( isset( $_POST['submit'] ) ) {
$edges = ( isset( $_POST['edges'] ) ) ? 'yes' : 'no';
$light = ( isset( $_POST['light'] ) ) ? 'yes' : 'no';
// . . .
}
While the approach above using single variables works, there's a much cleaner way of writing this with arrays.
Array example HTML:
<input type="checkbox" name="myCheckbox[]" value="edges">
<input type="checkbox" name="myCheckbox[]" value="light">
. . .
Array example PHP:
if ( isset( $_POST['submit'] ) ) {
// Each checkbox option should default to no.
$checkboxes = array(
'edges' => 'no',
'light' => 'no',
// . . . don't forget to add all your options here.
);
// Let's make sure we have some checkboxes posted.
if ( ! empty( $_POST['myCheckbox'] ) ) {
// Loop through each checked option.
foreach ( (array) $_POST['myCheckbox'] as $checked ) {
// If the checked option exists in our checkbox array, update value to yes.
if ( array_key_exists( $checked, $checkboxes ) ) {
$checkboxes[ $checked ] = 'yes';
}
}
}
// Do stuff with your checkbox values here...
}
Related Topics
Why Do Browsers Insert Tbody Element into Table Elements
How to Add a Custom Attribute to an HTML Tag
Margin-Top Push Outer Div Down
Why Does Styling the Background of the Body Element Affect the Entire Screen
Is ≪Img≫ Element Block Level or Inline Level
Is There a CSS Selector For the First Direct Child Only
How to Encode/Decode HTML Entities in Ruby
Making a Div Vertically Scrollable Using Css
Change Bullets Color of an HTML List Without Using Span
What's the Difference Between Disabled="Disabled" and Readonly="Readonly" for HTML Form Input Fields
How Does the "Position: Sticky;" Property Work
How to Create Your Own HTML Tag in Html5
How to Get This CSS Text-Decoration Override to Work
How to Remove the Arrow from a Select Element in Firefox
How to Customize ≪Input Type="File"≫
Add Border-Bottom to Table Row ≪Tr≫
Getting the Source HTML of the Current Page from Chrome Extension