Submit an HTML Form With Empty Checkboxes

Submit an HTML form with empty checkboxes

Unchecked radio or checkbox elements are not submitted as they are not considered as successful. So you have to check if they are sent using the isset or empty function.

if (isset($_POST['checkbox'])) {
// checkbox has been checked
}

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;
}
}

Checkbox value comes in as empty string through POST in PHP

Do you have any other <form> tags ahead or around this form? This is a shot in the dark, but I had this problem last week, and was pulling my hair out, until I found that the form I was looking at, was actually nested inside another form, and that changes the behavior. If the other form has the same named value, it can (in some cases, apparently) take precedence and prevent you from seeing the value that you think you are getting.

Enable submit button if input and checkbox aren't empty


As of jQuery 3.0, .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.

Please don't use the deprecated method bind() use on() instead :

$('#first, #last, #pass').on('keyup', function() {
if (allFilled()) $('#register').removeAttr('disabled');
});

Hope this helps.





$('#first, #last, #pass').on('keyup', function() {

if (allFilled()) $('#register').removeAttr('disabled');

});


function allFilled() {

var filled = true;


$('body input').each(function() {

if ($(this).val() == '' && $('#checkbox').prop('checked') == false) filled = false;

});

return filled

};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>

Username

<br />

<input type="text" id="first" name="first" />

<br /> First

<br />

<input type="text" id="last" name="last" />

<br /> Last

<br />

<input type="text" id="pass" name="pass" />

<br /> Password

<br />

<input type="checkbox" class="checkbox" id="checkbox" name="checkbox" />

<br />

<input type="submit" id="register" disabled value="Register" />

</form>

<div id="test">

</div>

IE Form Submit Empty yet works with type=checkbox

From @stephenmuecke 's comment I tested the buttons without the JavaScript

onclick="submitForm.submit();"

As obviously this was competing with the input type="submit", removing the onclick attribute solved any issues.

So in the end the error was all my fault, hopefully this info helps someone else notice this quicker than I did.

Not submit any value if checkbox is empty

You have a widget.

The widget is interfering with the normal passing of form element values.

I solved it by adding an empty value to the original select after creating the multiple option





$(function() {
$("#test").CreateMultiCheckBox({
width: '100%',
defaultText: 'Select Tags',
height: '250px'
});

// add an empty value to the select AFTER creating the multioption

$("#test").html(`<option value=""></option>`+$("#test").html())

// comment the next lines out to allow submission
$("#myForm").on("submit", function(e) {
console.log($(this).serialize())
e.preventDefault();
})

$(document).on("click", ".MultiCheckBox", function() {
var detail = $(this).next();
detail.show();
});

$(document).on("click", ".MultiCheckBoxDetailHeader input", function(e) {
e.stopPropagation();
var hc = $(this).prop("checked");
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", hc);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});

$(document).on("click", ".MultiCheckBoxDetailHeader", function(e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});

$(document).on("click", ".MultiCheckBoxDetail .cont input", function(e) {
e.stopPropagation();
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();

var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});

$(document).on("click", ".MultiCheckBoxDetail .cont", function(e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);

var multiCheckBoxDetail = $(this).closest(".MultiCheckBoxDetail");
var multiCheckBoxDetailBody = $(this).closest(".MultiCheckBoxDetailBody");
multiCheckBoxDetail.next().UpdateSelect();

var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});

$(document).mouseup(function(e) {
var container = $(".MultiCheckBoxDetail");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
});

var defaultMultiCheckBoxOption = {
width: '220px',
defaultText: 'Select Below',
height: '200px'
};

jQuery.fn.extend({
CreateMultiCheckBox: function(options) {

var localOption = {};
localOption.width = (options != null && options.width != null && options.width != undefined) ? options.width : defaultMultiCheckBoxOption.width;
localOption.defaultText = (options != null && options.defaultText != null && options.defaultText != undefined) ? options.defaultText : defaultMultiCheckBoxOption.defaultText;
localOption.height = (options != null && options.height != null && options.height != undefined) ? options.height : defaultMultiCheckBoxOption.height;

this.hide();
this.attr("multiple", "multiple");
var divSel = $("<div class='MultiCheckBox'>" + localOption.defaultText + "<span class='k-icon k-i-arrow-60-down'><svg aria-hidden='true' focusable='false' data-prefix='fas' data-icon='sort-down' role='img' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' class='svg-inline--fa fa-sort-down fa-w-10 fa-2x'><path fill='currentColor' d='M41 288h238c21.4 0 32.1 25.9 17 41L177 448c-9.4 9.4-24.6 9.4-33.9 0L24 329c-15.1-15.1-4.4-41 17-41z' class=''></path></svg></span></div>").insertBefore(this);
divSel.css({
"width": localOption.width
});

var detail = $("<div class='MultiCheckBoxDetail'><div class='MultiCheckBoxDetailHeader'><input type='checkbox' class='mulinput' value='-1982' /><div>Select All</div></div><div class='MultiCheckBoxDetailBody'></div></div>").insertAfter(divSel);
detail.css({
"width": parseInt(options.width) + 10,
"max-height": localOption.height
});
var multiCheckBoxDetailBody = detail.find(".MultiCheckBoxDetailBody");

this.find("option").each(function() {
var val = $(this).attr("value");

if (val == undefined)
val = '';

multiCheckBoxDetailBody.append("<div class='cont'><div><input type='checkbox' class='mulinput' value='" + val + "' /></div><div>" + $(this).text() + "</div></div>");
});

multiCheckBoxDetailBody.css("max-height", (parseInt($(".MultiCheckBoxDetail").css("max-height")) - 28) + "px");
},
UpdateSelect: function() {
var arr = [];

this.prev().find(".mulinput:checked").each(function() {
arr.push($(this).val());
});

this.val(arr);
},
});
.MultiCheckBox {
border: 1px solid #e2e2e2;
padding: 5px;
border-radius: 4px;
cursor: pointer;
}

.MultiCheckBox .k-icon {
font-size: 15px;
float: right;
font-weight: bolder;
margin-top: -7px;
height: 10px;
width: 14px;
color: #787878;
}

.MultiCheckBoxDetail {
display: none;
position: absolute;
border: 1px solid #e2e2e2;
overflow-y: hidden;
}

.MultiCheckBoxDetailBody {
overflow-y: scroll;
background: white;
}

.MultiCheckBoxDetail .cont {
clear: both;
overflow: hidden;
padding: 2px;
}

.MultiCheckBoxDetail .cont:hover {
background-color: #cfcfcf;
}

.MultiCheckBoxDetailBody>div>div {
float: left;
}

.MultiCheckBoxDetail>div>div:nth-child(1) {}

.MultiCheckBoxDetailHeader {
overflow: hidden;
position: relative;
height: 28px;
background-color: #3d3d3d;
}

.MultiCheckBoxDetailHeader>input {
position: absolute;
top: 4px;
left: 3px;
}

.MultiCheckBoxDetailHeader>div {
position: absolute;
top: 5px;
left: 24px;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<div class="form-row">
<div class="form-group col">
<select name="tag[]" class="form-control" id="test">
<option value="1">Allergy</option>
<option value="2">Full Day</option>
<option value="3">Subsidy</option>
<option value="4">Toddler</option>
</select>
</div>
</div>
<input type="submit" />
</form>

function empty() doesn't work on checkboxes

You need to have a value for the checkbox (e.g. value='ON')

Because empty string is also regarded as "empty" (see the documentation here )

Change

<input class="form-check-input" type="checkbox" value="" 
id="checkbox-ambulance" name="checkbox-ambulance">

to

<input class="form-check-input" type="checkbox" value="ON" 
id="checkbox-ambulance" name="checkbox-ambulance">

So a sample will be like:

<?php

if ($_POST["submit"]) {

if (empty($_POST['checkbox-ambulance'])) {
$x = "unchecked";
} else {
$x = "checked";
}

echo $x;
echo "<br>";
echo date('l jS \of F Y h:i:s A');

}
?>

<form action=# method=POST>
Tick this box (or not):
<input class="form-check-input" type="checkbox" value="ON"
id="checkbox-ambulance" name="checkbox-ambulance">
<br>
<input type="submit" name="submit">
</form>

See this sample link:

http://www.createchhk.com/SO/testSO22Jan2022.php#

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.

How to disable submit input field until all required fields and checkboxes are empty

You can apply the required attribute to your inputs. When one of the inputs in a form has this attribute but has not been filled at the moment the Submit button is clicked, the form will not be submitted. Instead, the invalid event will be fired on all inputs whose values are missing. You can use it to let the user know what needs to be filled in.

Here is a minimal example using React:





const { useState } = React;

function Input(props) {
const [invalid, setInvalid] = useState(false);

const handleInvalid = event => {
event.preventDefault();
console.log('Invalid');
setInvalid(true);
};

const handleChange = () => setInvalid(false);

const className = invalid ? 'invalid' : '';

return (
<div className={className}>
<input {...props} onInvalid={handleInvalid} onChange={handleChange} />
{props.type === "checkbox" && (
<label htmlFor={props.id}>
{props.label}
</label>
)}
</div>
);
}

function Form() {
const handleSubmit = event => {
event.preventDefault();
console.log('Submit');
};

return (
<form onSubmit={handleSubmit}>
<Input name="name" placeholder="Name" required />
<Input type="checkbox" name="accept" id="accept" label="I accept Terms of Usage" required />
<button>Submit</button>
</form>
);
}

ReactDOM.render(<Form />, document.getElementById('root'));
.invalid input[type=text], .invalid input:not([type]) {
border: 2px solid red;
}

.invalid label {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>


Related Topics



Leave a reply



Submit