Making 'file' input element mandatory (required) - html

I want to make (an HTML) 'file' input element mandatory: something like
<input type='file' required = 'required' .../>
But it is not working.
I saw this WW3 manual which states 'required' attribute is new to HTML 5. But I am not using HTML 5 in the project I am working which doesn't support the new feature.
Any idea?

Thanks to HTML5, it is as easy as this:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>

You can do it using Jquery like this:-
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadfile').val();
if(imgVal=='')
{
alert("empty input file");
return false;
}
});
});
</script>
<input type="file" name="image" id="uploadfile" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />

As of now in 2017, I am able to do this-
<input type='file' required />
and when you submit the form, it asks for file.

You could create a polyfill that executes on the form submit. For example:
/* Attach the form event when jQuery loads. */
$(document).ready(function(e){
/* Handle any form's submit event. */
$("form").submit(function(e){
e.preventDefault(); /* Stop the form from submitting immediately. */
var continueInvoke = true; /* Variable used to avoid $(this) scope confusion with .each() function. */
/* Loop through each form element that has the required="" attribute. */
$("form input[required]").each(function(){
/* If the element has no value. */
if($(this).val() == ""){
continueInvoke = false; /* Set the variable to false, to indicate that the form should not be submited. */
}
});
/* Read the variable. Detect any items with no value. */
if(continueInvoke == true){
$(this).submit(); /* Submit the form. */
}
});
});
This script waits for the form to be submitted, then loops though each form element that has the required attribute has a value entered. If everything has a value, it submits the form.
An example element to be checked could be:
<input type="file" name="file_input" required="true" />
(You can remove the comments & minify this code when using it on your website)

var imgVal = $('[type=file]').val();
Similar to Vivek's suggestion, but now you have a more generic selector of the input file and you don't rely on specific ID or class.
See this demo.

Some times the input field is not bound with the form.
I might seem within the <form> and </form> tags but it is outside these tags.
You can try applying the form attribute to the input field to make sure it is related to your form.
<input type="file" name="" required="" form="YOUR-FORM-ID-HERE" />
I hope it helps.

All statements above are entirely correct. However, it is possible for a malicious user to send a POST request without using your form in order to generate errors. Thus, HTML and JS, while offering a user-friendly approach, will not prevent these sorts of attacks. To do so, make sure that your server double checks request data to make sure nothing is empty.

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>

Related

Regex pattern for preventing leading whitespace in HTML input

<input type="text" pattern="^[a-zA-Z1-9].*">
How can I restrict the following input element from having leading whitespace, ie, it should always start with a character except a whitespace.
This answer suggested I use pattern="^[a-zA-Z1-9].*" but it doesn't seem to work.
EDIT:
It works only if I wrap it in a form tag and a submit button. Clicking the button triggers the error. But I want to be able to restrict users from entering whitespace on the input box itself.
To achieve this without a form-tag we can use a JavaScript live input filter like this:
var noLeadingSpace = /^\w.*$/;
$("input")
.data("oldValue", "")
.bind("input propertychange", function() {
var $this = $(this);
var newValue = $this.val();
if (!noLeadingSpace.test(newValue))
return $this.val($this.data("oldValue"));
return $this.data("oldValue", newValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
It does work, but it will be validated if you try to send a form.
function myValidator(v){
var input = document.getElementById('uglyWay')
if(input){
input.value = input.value.replace(/ /g, '')
}
}
<form>
<input id="uglyWay" oninput='myValidator()' type="text" pattern="^[a-zA-Z1-9].*">
<button type="submit">Send</button>
</form>
The Following Regex mentioned in question Works without wrapping inside form tag
input[type="text"]:valid{
background:green;
}
input[type="text"]:invalid{
background:red;
}
<input type="text" pattern="^[a-zA-Z1-9].*">

I made the html & js code to do the validation check. But the data is submitted before checking the data

<form name="mForm" action="${pageContext.request.contextPath}/login/insertSeller.do" method="post">
id : <input type="text" name="id" />
<input type="submit" value="register" onClick="doAction()" />
</form>
<script>
function doAction() {
var f = document.mForm;
var id = f.id;
if (id.value == "") {
alert("insert your id");
id.focus();
return false;
}
return true;
}
</script>
Is there any error to correct?
If I click the button, the alert window opens with a message,
but the data is submitted without the validation check.
What do I need to do?
Please help me :)
You really shouldn’t have inline event handlers in modern HTML. Nevertheless, you could try the following:
<input … onclick="return doAction()">
The return in the onclick causes the input to wait for permission.
For the sake of completeness, here is how I would do it in a modern browser:
First, use a button instead:
<button type="submit">register</button>
Second, give your button a name
<button name="register" type="submit">register</button>
You can give a name to the older style input element, and the process will still work.
Next, add the following to your JavaScript:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('button[name="register"]).onclick=doAction;
},false);
The main function acts as a startup script. The point of it is that it is waiting for the DOM to have loaded. Otherwise it’s not possible to look for elements that aren’t there yet.
Note that you assign to the onclick event handler the name of the function.

Angular, validate form when submitting from outside form [duplicate]

Given this code:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?
Live test: http://jsfiddle.net/dzjV4/1/
You can create directive which you can then attach to <a class="btn".... Check this jsfiddle
http://jsfiddle.net/dzjV4/2/
Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...
for (control of $scope.[form name].$$controls) {
control.$setDirty();
control.$validate();
}
You can try the above codes. Make it running before submit.
Ideally there'd be a programmatic way to cause validation to re-run across a form. I have not investigated that completely but had a situation that required multiple controls to be re-validated based on different data in the scope -- without the user interacting with the individual controls. This arose because the form had two action buttons which each required different validation rules be in play when they were clicked.
The UI requirement changed before I fully implemented forcing re-validation but before it did I got most of what I needed by copying and then re-setting the form's data. This forced re-validation across the form within the current scope. Basically, it's along the lines of the following (not tested, but taken from the code that was working). In this case the form's data was bound to the properties in one object.
var formData = $parse(<form's model>);
var dataCopy = angular.copy( formData($scope) );
formData.assign( $scope, dataCopy );
This may or may not be acceptable, but if you can get away with the SUBMIT button being disabled until the form is completed, you can do this:
<form name="formName">
<input ng-required="true" />
</form>
<button ng-click="someFunction()" ng-disabled="formName.$invalid" />
It's also worth noting that this works in IE9 (if you're worried about that).
Give your form a name:
<div ng-controller="MyCtrl">
<form name="myForm">
<input name="myInput" />
</form>
</div>
So you can access your form validation status on your scope.
app.controller('MyCtrl', function($scope) {
$scope.myForm.$valid // form valid or not
$scope.myForm.myInput // input valid or not
// do something with myForm, e.g. display a message manually
})
angular doc
There is no way to trigger browser form behavior outside of a form. You have to do this manually.
Since my form fields only show validation messages if a field is invalid, and has been touched by the user:
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}

Form button not working in IE11

I have created a form with a submit button, the submit button is outside the actual form but its targeting the form using the form attribute for example.
<form id="myform">
</form>
<button form="myform"></button>
I apologize for the week example. This is working accross all browsers except IE 11. IE 8-10 is working 100%. Any ideas on how I can fix this. I prefer not writing scripts. I can do this with jQuery but I prefer to just keep it clean if possible
This is a solution with just a click event and a line of css. ( Minimal )
If your button has to be outside the form due to User Interface design.
I would suggest you add an input submit/button inside the form:
<form id="myform">
<input type="button" value="Submit" class="myButton" />
</form>
<button id="outerBtn">Submit</button>
Hide the input:
.myButton {display:none;} OR {visibility:none;}
Use jQuery to trigger click the input button inside the form:
$('#outerBtn').on('click', function(e){
e.preventDefault();
$('.myButton').trigger('click');
});
Just some quick answer. Should be alright.
If you do not want to write script, I would suggest you just keep your input button/submit inside the form.
<form id="form-any-name">
<input type="button" value="Submit" class="myButton" />
</form>
<button type="submit">Submit</button>
<script type="text/javascript">
$(document).ready(function() {
$('button[type=\'submit\']').on('click', function() {
$("form[id*='form-']").submit();
});
});
</script>
Simply include document on ready submit catcher you can place that code in main js file since we catching dinamicaly form id starting with form- so in other pages you can have the different foms:)
I would like to post my answer as this post helped me a lot and I came with an idea that works if you want to add the "button outside the form" functionality on older browsers.
I use JQuery but I dont think I would be a major problem to use pure JS as it's not complicated code.
Just create a class just as some of the answers suggested here
.hiddenSubmitButton {
display: none;
}
$("body").on("click", "button[form]", function () {
/*This will get the clicks when make on buttons with form attribute
* it's useful as we commonly use this property when we place buttons that submit forms outside the form itself
*/
let form, formProperty, formAttribute, code, newButtonID;
formProperty = $(this).prop("form");
if (!(formProperty === null || formProperty === "")) {//Most browsers that don't wsupport form property will return null others ""
return; //Browsers that support the form property won't continue
}
formAttribute = $(this).attr("form");
form = $("#" + formAttribute);
newButtonID = formAttribute + "_hiddenButton";
if (document.getElementById(newButtonID) !== null) {
$("#" + newButtonID).click();
return;
}
code = '<input id="' + newButtonID + '" class="hiddenSubmitButton" type="submit" value="Submit" />';
$(form).append(code);
setTimeout(function () {
$("#" + newButtonID).click();
}, 50);
});
One thing I like about creating buttons outside the form is that they allow us to custom the design more easily and we can use this code and it will work on old browsers and also, the browser will use its HTML form validator.
IE understands 'for', you can use "label for=''".
<label for="form_one_submit">Button one</label>
<form action="" id="form_one">
<span></span>
<input type="submit" id="form_one_submit" style="visibility:hidden;">
</form>

POST unchecked HTML checkboxes

I've got a load of checkboxes that are checked by default. My users will probably uncheck a few (if any) of the checkboxes and leave the rest checked.
Is there any way to make the form POST the checkboxes that are not checked, rather than the ones that are checked?
The solution I liked the most so far is to put a hidden input with the same name as the checkbox that might not be checked. I think it works so that if the checkbox isn't checked, the hidden input is still successful and sent to the server but if the checkbox is checked it will override the hidden input before it. This way you don't have to keep track of which values in the posted data were expected to come from checkboxes.
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
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;
}
}
I solved it by using vanilla JavaScript:
<input type="hidden" name="checkboxName" value="0"><input type="checkbox" onclick="this.previousSibling.value=1-this.previousSibling.value">
Be careful not to have any spaces or linebreaks between this two input elements!
You can use this.previousSibling.previousSibling to get "upper" elements.
With PHP you can check the named hidden field for 0 (not set) or 1 (set).
My personal favorite is to add a hidden field with the same name that will be used if the check-box is unchecked. But the solution is not as easy as it may seems.
If you add this code:
<form>
<input type='hidden' value='0' name='selfdestruct'>
<input type='checkbox' value='1' name='selfdestruct'>
</form>
The browser will not really care about what you do here. The browser will send both parameters to the server, and the server has to decide what to do with them.
PHP for example takes the last value as the one to use (see: Authoritative position of duplicate HTTP GET query keys)
But other systems I worked with (based on Java) do it the way around - they offer you only the first value.
.NET instead will give you an array with both elements instead
I'll try to test this with node.js, Python and Perl at sometime.
you don't need to create a hidden field for all checkboxes just copy my code.
it will change the value of checkbox if not checked the value will assign 0 and if checkbox checked then assign value into 1
$("form").submit(function () {
var this_master = $(this);
this_master.find('input[type="checkbox"]').each( function () {
var checkbox_this = $(this);
if( checkbox_this.is(":checked") == true ) {
checkbox_this.attr('value','1');
} else {
checkbox_this.prop('checked',true);
//DONT' ITS JUST CHECK THE CHECKBOX TO SUBMIT FORM DATA
checkbox_this.attr('value','0');
}
})
})
A common technique around this is to carry a hidden variable along with each checkbox.
<input type="checkbox" name="mycheckbox" />
<input type="hidden" name="mycheckbox.hidden"/>
On the server side, we first detect list of hidden variables and for each of the hidden variable, we try to see if the corresponding checkbox entry is submitted in the form data or not.
The server side algorithm would probably look like:
for input in form data such that input.name endswith .hidden
checkboxName = input.name.rstrip('.hidden')
if chceckbName is not in form, user has unchecked this checkbox
The above doesn't exactly answer the question, but provides an alternate means of achieving similar functionality.
I know this question is 3 years old but I found a solution that I think works pretty well.
You can do a check if the $_POST variable is assigned and save it in a variable.
$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';
the isset() function checks if the $_POST variable is assigned. By logic if it is not assigned then the checkbox is not checked.
$('input[type=checkbox]').on("change",function(){
var target = $(this).parent().find('input[type=hidden]').val();
if(target == 0)
{
target = 1;
}
else
{
target = 0;
}
$(this).parent().find('input[type=hidden]').val(target);
});
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
<input type="checkbox" />
<input type="hidden" name="test_checkbox[]" value="0" />
</p>
If you leave out the name of the checkbox it doesn't get passed.
Only the test_checkbox array.
You can do some Javascript in the form's submit event. That's all you can do though, there's no way to get browsers to do this by themselves. It also means your form will break for users without Javascript.
Better is to know on the server which checkboxes there are, so you can deduce that those absent from the posted form values ($_POST in PHP) are unchecked.
I also like the solution that you just post an extra input field, using JavaScript seems a little hacky to me.
Depending on what you use for you backend will depend on which input goes first.
For a server backend where the first occurrence is used (JSP) you should do the following.
<input type="checkbox" value="1" name="checkbox_1"/>
<input type="hidden" value="0" name="checkbox_1"/>
For a server backend where the last occurrence is used (PHP,Rails) you should do the following.
<input type="hidden" value="0" name="checkbox_1"/>
<input type="checkbox" value="1" name="checkbox_1"/>
For a server backend where all occurrences are stored in a list data type ([],array). (Python / Zope)
You can post in which ever order you like, you just need to try to get the value from the input with the checkbox type attribute. So the first index of the list if the checkbox was before the hidden element and the last index if the checkbox was after the hidden element.
For a server backend where all occurrences are concatenated with a comma (ASP.NET / IIS)
You will need to (split/explode) the string by using a comma as a delimiter to create a list data type. ([])
Now you can attempt to grab the first index of the list if the checkbox was before the hidden element and grab the last index if the checkbox was after the hidden element.
image source
I would actually do the following.
Have my hidden input field with the same name with the checkbox input
<input type="hidden" name="checkbox_name[]" value="0" />
<input type="checkbox" name="checkbox_name[]" value="1" />
and then when i post I first of all remove the duplicate values picked up in the $_POST array, atfer that display each of the unique values.
$posted = array_unique($_POST['checkbox_name']);
foreach($posted as $value){
print $value;
}
I got this from a post remove duplicate values from array
"I've gone with the server approach. Seems to work fine - thanks. – reach4thelasers Dec 1 '09 at 15:19" I would like to recommend it from the owner. As quoted: javascript solution depends on how the server handler (I didn't check it)
such as
if(!isset($_POST["checkbox"]) or empty($_POST["checkbox"])) $_POST["checkbox"]="something";
Most of the answers here require the use of JavaScript or duplicate input controls. Sometimes this needs to be handled entirely on the server-side.
I believe the (intended) key to solving this common problem is the form's submission input control.
To interpret and handle unchecked values for checkboxes successfully you need to have knowledge of the following:
The names of the checkboxes
The name of the form's submission input element
By checking whether the form was submitted (a value is assigned to the submission input element), any unchecked checkbox values can be assumed.
For example:
<form name="form" method="post">
<input name="value1" type="checkbox" value="1">Checkbox One<br/>
<input name="value2" type="checkbox" value="1" checked="checked">Checkbox Two<br/>
<input name="value3" type="checkbox" value="1">Checkbox Three<br/>
<input name="submit" type="submit" value="Submit">
</form>
When using PHP, it's fairly trivial to detect which checkboxes were ticked.
<?php
$checkboxNames = array('value1', 'value2', 'value3');
// Persisted (previous) checkbox state may be loaded
// from storage, such as the user's session or a database.
$checkboxesThatAreChecked = array();
// Only process if the form was actually submitted.
// This provides an opportunity to update the user's
// session data, or to persist the new state of the data.
if (!empty($_POST['submit'])) {
foreach ($checkboxNames as $checkboxName) {
if (!empty($_POST[$checkboxName])) {
$checkboxesThatAreChecked[] = $checkboxName;
}
}
// The new state of the checkboxes can be persisted
// in session or database by inspecting the values
// in $checkboxesThatAreChecked.
print_r($checkboxesThatAreChecked);
}
?>
Initial data could be loaded on each page load, but should be only modified if the form was submitted. Since the names of the checkboxes are known beforehand, they can be traversed and inspected individually, so that the the absence of their individual values indicates that they are not checked.
I've tried Sam's version first.
Good idea, but it causes there to be multiple elements in the form with the same name. If you use any javascript that finds elements based on name, it will now return an array of elements.
I've worked out Shailesh's idea in PHP, it works for me.
Here's my code:
/* Delete '.hidden' fields if the original is present, use '.hidden' value if not. */
foreach ($_POST['frmmain'] as $field_name => $value)
{
// Only look at elements ending with '.hidden'
if ( !substr($field_name, -strlen('.hidden')) ) {
break;
}
// get the name without '.hidden'
$real_name = substr($key, strlen($field_name) - strlen('.hidden'));
// Create a 'fake' original field with the value in '.hidden' if an original does not exist
if ( !array_key_exists( $real_name, $POST_copy ) ) {
$_POST[$real_name] = $value;
}
// Delete the '.hidden' element
unset($_POST[$field_name]);
}
You can also intercept the form.submit event and reverse check before submit
$('form').submit(function(event){
$('input[type=checkbox]').prop('checked', function(index, value){
return !value;
});
});
I use this block of jQuery, which will add a hidden input at submit-time to every unchecked checkbox. It will guarantee you always get a value submitted for every checkbox, every time, without cluttering up your markup and risking forgetting to do it on a checkbox you add later. It's also agnostic to whatever backend stack (PHP, Ruby, etc.) you're using.
// Add an event listener on #form's submit action...
$("#form").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function(index) {
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
input.attr('value', "0"); // or 'off', 'false', 'no', whatever
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
$('form').submit(function () {
$(this).find('input[type="checkbox"]').each( function () {
var checkbox = $(this);
if( checkbox.is(':checked')) {
checkbox.attr('value','1');
} else {
checkbox.after().append(checkbox.clone().attr({type:'hidden', value:0}));
checkbox.prop('disabled', true);
}
})
});
I see this question is old and has so many answers, but I'll give my penny anyway.
My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true
$('form').submit(function(e){
var b = $("input:checkbox:not(:checked)");
$(b).each(function () {
$(this).val(0); //Set whatever value you need for 'not checked'
$(this).attr("checked", true);
});
return true;
});
this way you will have a $_POST array like this:
Array
(
[field1] => 1
[field2] => 0
)
What I did was a bit different. First I changed the values of all the unchecked checkboxes. To "0", then selected them all, so the value would be submitted.
function checkboxvalues(){
$("#checkbox-container input:checkbox").each(function({
if($(this).prop("checked")!=true){
$(this).val("0");
$(this).prop("checked", true);
}
});
}
I would prefer collate the $_POST
if (!$_POST['checkboxname']) !$_POST['checkboxname'] = 0;
it minds, if the POST doesn't have have the 'checkboxname'value, it was unckecked so, asign a value.
you can create an array of your ckeckbox values and create a function that check if values exist, if doesn`t, it minds that are unchecked and you can asign a value
Might look silly, but it works for me. The main drawback is that visually is a radio button, not a checkbox, but it work without any javascript.
HTML
Initialy checked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="a" value="1" checked>
<input type="radio" name="a" value="0">
</span>
<br/>
Initialy unchecked
<span><!-- set the check attribute for the one that represents the initial value-->
<input type="radio" name="b" value="1">
<input type="radio" name="b" value="0" checked>
</span>
and CSS
span input
{position: absolute; opacity: 0.99}
span input:checked
{z-index: -10;}
span input[value="0"]
{opacity: 0;}
fiddle here
I'd like to hear any problems you find with this code, cause I use it in production
The easiest solution is a "dummy" checkbox plus hidden input if you are using jquery:
<input id="id" type="hidden" name="name" value="1/0">
<input onchange="$('#id').val(this.checked?1:0)" type="checkbox" id="dummy-id"
name="dummy-name" value="1/0" checked="checked/blank">
Set the value to the current 1/0 value to start with for BOTH inputs, and checked=checked if 1. The input field (active) will now always be posted as 1 or 0. Also the checkbox can be clicked more than once before submission and still work correctly.
Example on Ajax actions is(':checked') used jQuery instead of .val();
var params = {
books: $('input#users').is(':checked'),
news : $('input#news').is(':checked'),
magazine : $('input#magazine').is(':checked')
};
params will get value in TRUE OR FALSE..
Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.
Since I store values 'Y' and 'N' in my database and represent them via checked and unchecked checkboxes on page, I added hidden field for each value (checkbox) with 'Y' and 'N' values then use checkboxes just for visual representation, and use simple JavaScript function check() to set value of if according to selection.
<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>
use one JavaScript onclick listener and call function check() for each checkboxe on my web page:
function check(me)
{
if(me.checked)
{
me.previousSibling.previousSibling.value='Y';
}
else
{
me.previousSibling.previousSibling.value='N';
}
}
This way 'Y' or 'N' values are always sent to server side script, it knows what are fields that should be updated and there's no need for conversion of checbox "on" value into 'Y' or not received checkbox into 'N'.
NOTE: white space or new line is also a sibling so here I need .previousSibling.previousSibling.value. If there's no space between then only .previousSibling.value
You don't need to explicitly add onclick listener like before, you can use jQuery library to dynamically add click listener with function to change value to all checkboxes in your page:
$('input[type=checkbox]').click(function()
{
if(this.checked)
{
$(this).prev().val('Y');
}
else
{
$(this).prev().val('N');
}
});
#cpburnz got it right but to much code, here is the same idea using less code:
JS:
// jQuery OnLoad
$(function(){
// Listen to input type checkbox on change event
$("input[type=checkbox]").change(function(){
$(this).parent().find('input[type=hidden]').val((this.checked)?1:0);
});
});
HTML (note the field name using an array name):
<div>
<input type="checkbox" checked="checked">
<input type="hidden" name="field_name[34]" value="1"/>
</div>
<div>
<input type="checkbox">
<input type="hidden" name="field_name[35]" value="0"/>
</div>
<div>
And for PHP:
<div>
<input type="checkbox"<?=($boolean)?' checked="checked"':''?>>
<input type="hidden" name="field_name[<?=$item_id?>]" value="<?=($boolean)?1:0?>"/>
</div>
All answers are great, but if you have multiple checkboxes in a form with the same name and you want to post the status of each checkbox. Then i have solved this problem by placing a hidden field with the checkbox (name related to what i want).
<input type="hidden" class="checkbox_handler" name="is_admin[]" value="0" />
<input type="checkbox" name="is_admin_ck[]" value="1" />
then control the change status of checkbox by below jquery code:
$(documen).on("change", "input[type='checkbox']", function() {
var checkbox_val = ( this.checked ) ? 1 : 0;
$(this).siblings('input.checkbox_handler').val(checkbox_val);
});
now on change of any checkbox, it will change the value of related hidden field. And on server you can look only to hidden fields instead of checkboxes.
Hope this will help someone have this type of problem. cheer :)
You can add hidden elements before submitting form.
$('form').submit(function() {
$(this).find('input[type=checkbox]').each(function (i, el) {
if(!el.checked) {
var hidden_el = $(el).clone();
hidden_el[0].checked = true;
hidden_el[0].value = '0';
hidden_el[0].type = 'hidden'
hidden_el.insertAfter($(el));
}
})
});
The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.
In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.
if(!isset($_POST['checkbox1']))
{
$checkboxValue = false;
} else {
$checkboxValue = $_POST['checkbox1'];
}
But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.
function SubmitCheckBox(obj) {
obj.value = obj.checked ? "on" : "off";
obj.checked = true;
return obj.form.submit();
}
<input type=checkbox name="foo" onChange="return SubmitCheckBox(this);">
If you want to submit an array of checkbox values (including un-checked items) then you could try something like this:
<form>
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Dog
<input type="hidden" value="0" name="your_checkbox_array[]"><input type="checkbox">Cat
</form>
$('form').submit(function(){
$('input[type="checkbox"]:checked').prev().val(1);
});