Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?
And if no value data is supplied, is the default value always "on"?
Assuming the above is correct, is this consistent behaviour across all browsers?
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.
In HTML, each <input /> element is associated with a single (but not unique) name and value pair. This pair is sent in the subsequent request (in this case, a POST request body) only if the <input /> is "successful".
So if you have these inputs in your <form> DOM:
<input type="text" name="one" value="foo" />
<input type="text" name="two" value="bar" disabled="disabled" />
<input type="text" name="three" value="first" />
<input type="text" name="three" value="second" />
<input type="checkbox" name="four" value="baz" />
<input type="checkbox" name="five" value="baz" checked="checked" />
<input type="checkbox" name="six" value="qux" checked="checked" disabled="disabled" />
<input type="checkbox" name="" value="seven" checked="checked" />
<input type="radio" name="eight" value="corge" />
<input type="radio" name="eight" value="grault" checked="checked" />
<input type="radio" name="eight" value="garply" />
Will generate these name+value pairs which will be submitted to the server:
one=foo
three=first
three=second
five=baz
eight=grault
Notice that:
two and six were excluded because they had the disabled attribute set.
three was sent twice because it had two valid inputs with the same name.
four was not sent because it is a checkbox that was not checked
six was not sent despite being checked because the disabled attribute has a higher precedence.
seven does not have a name="" attribute sent, so it is not submitted.
With respect to your question: you can see that a checkbox that is not checked will therefore not have its name+value pair sent to the server - but other inputs that share the same name will be sent with it.
Frameworks like ASP.NET MVC work around this by (surreptitiously) pairing every checkbox input with a hidden input in the rendered HTML, like so:
#Html.CheckBoxFor( m => m.SomeBooleanProperty )
Renders:
<input type="checkbox" name="SomeBooleanProperty" value="true" />
<input type="hidden" name="SomeBooleanProperty" value="false" />
If the user does not check the checkbox, then the following will be sent to the server:
SomeBooleanProperty=false
If the user does check the checkbox, then both will be sent:
SomeBooleanProperty=true
SomeBooleanProperty=false
But the server will ignore the =false version because it sees the =true version, and so if it does not see =true it can determine that the checkbox was rendered and that the user did not check it - as opposed to the SomeBooleanProperty inputs not being rendered at all.
If checkbox isn't checked then it doesn't contribute to the data sent on form submission.
HTML5 section 4.10.22.4 Constructing the form data set describes the way form data is constructed:
If any of the following conditions are met, then skip these substeps
for this element:
[...]
The field element is an input element whose type
attribute is in the Checkbox state and whose checkedness is false.
and then the default valued on is specified if value is missing:
Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then run these further nested substeps:
If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".
Thus unchecked checkboxes are skipped during form data construction.
Similar behavior is required under HTML4. It's reasonable to expect this behavior from all compliant browsers.
Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs
JS:
var chk = $('input[type="checkbox"]');
chk.each(function(){
var v = $(this).attr('checked') == 'checked'?1:0;
$(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
});
chk.change(function(){
var v = $(this).is(':checked')?1:0;
$(this).next('input[type="hidden"]').val(v);
});
HTML:
<label>Active</label><input rel="active" type="checkbox" />
Is it standard behaviour for browsers to only send the checkbox input
value data if it is checked upon form submission?
Yes, because otherwise there'd be no solid way of determining if the checkbox was actually checked or not (if it changed the value, the case may exist when your desired value if it were checked would be the same as the one that it was swapped to).
And if no value data is supplied, is the default value always "on"?
Other answers confirm that "on" is the default. However, if you are not interested in the value, just use:
if (isset($_POST['the_checkbox'])){
// name="the_checkbox" is checked
}
None of the above answers satisfied me.
I found the best solution is to include a hidden input before each checkbox input with the same name.
<input type="hidden" name="foo[]" value="off"/>
<input type="checkbox" name="foo[]"/>
Then on the server side, using a little algorithm you can get something more like HTML should provide.
function checkboxHack(array $checkbox_input): array
{
$foo = [];
foreach($checkbox_input as $value) {
if($value === 'on') {
array_pop($foo);
}
$foo[] = $value;
}
return $foo;
}
This will be the raw input
array (
0 => 'off',
1 => 'on',
2 => 'off',
3 => 'off',
4 => 'on',
5 => 'off',
6 => 'on',
),
And the function will return
array (
0 => 'on',
1 => 'off',
2 => 'on',
3 => 'on',
)
input type="hidden" name="is_main" value="0"
input type="checkbox" name="is_main" value="1"
so you can control like this as I did in the application.
if it checks then send value 1 otherwise 0
From HTML 4 spec, which should be consistent across almost all browsers:
http://www.w3.org/TR/html401/interact/forms.html#checkbox
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.
Successful is defined as follows:
A successful control is "valid" for submission. Every successful
control has its control name paired with its current value as part of
the submitted form data set. A successful control must be defined
within a FORM element and must have a control name.
I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.
First I put a hidden input box in line with my checkbox , i.e.
<td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]" class="chk_milestone" ></td>
Now if all the checkboxes are un-selected then values returned by the hidden field will all be off.
For example, here with five dynamically inserted checkboxes, the form POSTS the following values:
'delete_milestone' =>
array (size=7)
0 => string 'off' (length=3)
1 => string 'off' (length=3)
2 => string 'off' (length=3)
3 => string 'on' (length=2)
4 => string 'off' (length=3)
5 => string 'on' (length=2)
6 => string 'off' (length=3)
This shows that only the 3rd and 4th checkboxes are on or checked.
In essence the dummy or hidden input field just indicates that everything is off unless there is an "on" below the off index, which then gives you the index you need without a single line of client side code.
.
Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.
Having the same problem with unchecked checkboxes that will not be send on forms submit, I came out with a another solution than mirror the checkbox items.
Getting all unchecked checkboxes with
var checkboxQueryString;
$form.find ("input[type=\"checkbox\"]:not( \":checked\")" ).each(function( i, e ) {
checkboxQueryString += "&" + $( e ).attr( "name" ) + "=N"
});
in your post
'your_field': your_field.is(':checked'),
I resolved the problem with this code:
HTML Form
<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>
and the javascript function by change the checkbox value form:
//change value of checkbox element
function changeValueCheckbox(element){
if(element.checked){
element.value='on';
}else{
element.value='off';
}
}
and the server checked if the data post is "on" or "off". I used playframework java
final Map<String, String[]> data = request().body().asFormUrlEncoded();
if (data.get("is-business")[0].equals('on')) {
login.setType(new MasterValue(Login.BUSINESS_TYPE));
} else {
login.setType(new MasterValue(Login.USER_TYPE));
}
Related
I have an input field which only allows number:
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" pattern="[0-9]+"/>
I set more parameters than needed just to check if it would work with these. Unluckily it didn't.
When I am using it on Chrome it works, but when I am using it on Safari it doesn't.
Unfortunately, many browsers will only validate the input for an input with type="number" upon form submission. In such a case, the following prompt will appear (example from Safari):
I've modified your snippet to remove any non-numeric input as it is entered. I have tested that this snippet works on the Chrome, Firefox and Safari.
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
If you were willing to forgo the stepper, you could avoid having a single non-numerical character remove the entire input:
<input class="border" type="text" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
In these snippets, we use:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');"
to remove all characters that would result in the value in the input not matching a typical numeric form (no leading zeroes, no more than one decimal point).
Be warned: while you can use HTML, CSS and JavaScript to restrict what users enter when using your website normally (known as 'client-side validation'), it is trivial to bypass the restrictions set this way.
If you are sending this data to a server for transformation, you should not trust that this data will only be numeric and of the form you expect. You should consider this type of validation to be purely for convenience's sake rather than providing any guarantee that the server will receive valid data.
The above series of "replace" did not work for me. Since my project is in Angular, I instead created a custom form field validator. That way, an error is presented to the user on invalid input (which prevents form submission):
public static numberInputValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isUndefinedOrEmpty(control?.value) || control.value <= min) {
return { numberRequired: true };
} else if(control.value > max) {
return { numberTooBig: true };
}
return null;
};
}
The only related attributes on the HTML input field are: type="number" step=".01"
To use it, add the validator to your FormControl in your FormGroup:
myControlName: new FormControl<undefined | number>(undefined, numberInputValidator(0, 100))
And even though the validator takes only number inputs, it will return numberRequired if the form field contains non-numeric characters.
You can then display custom error messages as such this (right after the <input> field) if using Angular Material form fields:
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberRequired">
<p>Amount must be greater than zero</p>
</mat-error>
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberTooBig">
<p>Amount must be less than or equal to 100</p>
</mat-error>
I have this input button: image
The code of input:
<div class="media">
<label class="col-form-label m-r-10">Status Of System</label>
<div class="media-body text-right icon-state">
<label class="switch">
<input
type="checkbox"
name="status"
value="{{ setting()->status == '1' ? 0 : 1 }}"
>
<span class="switch-state bg-primary"></span>
</label>
the setting()->status is helper function:
if (! function_exists('setting') ) {
function setting(){
return \App\Setting::first();
}
}
And in the column(status), the default is 1.
The problem is when I try to switch between 1 and 0. Notice value attribute in input I try to say if the column in database 1 put 0 else put 1 to switch the value, but this way does not run find! How can do something like this :(
If I correctly understand your question, try like that:
Check checkbox according setting value:
<input
type="checkbox"
name="status"
#if(1 === setting()->status) checked #endif
>
Here you retrieved status from database. If it exists and exactly equals 1, checkbox will be checked. If not - unchecked.
Next you want to change database value according this checkbox checked state.
Checkbox field appears in $request only if checkbox checked. So, try to refactor a bit your controller:
$setting = \App\Setting::first(); // your setting
$setting->status = isset($request->status) ? 1 : 0; // if status exists in request, it means that checkbox was checked
$setting->save(); // update your database row
The problem is just one:
when a checkbox isn't checked, it's value isn't inserted in the request. So you have to check before the update if that checkbox value exist.
So instead of
setting()->update($request->all());
you have to do
$params = $request->all();
if(!isset($params['status'])) $params['status'] = 1;
setting()->update($params);
Also on the internet there is another solution, which is to add a hidden input with the same name and with the value that you want if that checkbox isn't checked like this:
<input type="hidden" name="status" value="1">
But in my opinion, it's just a dirty workaround... but you can have a try
Welcome,
I have some problem with form and insert data to mysql.
My form have an input:
<inpu type="checkbox" name="check">
and this is my code to insert this form data to mysql.
if(isset($_POST['check'])) { //things to insert }
and when i select one checkbox code inserting every record, when i select all checkboxes its also inserting a every record (all data). But when i not select a checkbox insert is empty (good).
Whats wrong with this checkboxes?
Checkboxes are sent via POST only if checked. If they are unchecked, they are not sent. Maybe you expect value 'on' if checked, and value 'off' if unchecked, but no!, you will receive only 'on' if checked, nothing otherwise. So if you receive checkbox (check it with isset($_POST['checkbox_name']') variable in your post set 1, true, 'Y' or whatever you use for boolean value in your database. If you do not receive it !isset() then set 0, false, or 'N'. The same situation is with disabled INPUT elements. Their values are not sent t server.
<form action"processor.php" method="post">
<input name="data[]"><input type="checkbox" name="check[]">
<input name="data[]"><input type="checkbox" name="check[]">
<input name="data[]"><input type="checkbox" name="check[]">
<input type="submit" value="Save">
</form>
In your processor.php file:
$data=$_POST['data']; //array received
$checks=$_POST['check']; //array received (checked only)
foreach($checks as $key=>$check) //loop through all checks that are sent
{
$value=$data[$key]; //do whatever you want with corresponding data
}
I'm facing the well known Chrome's "not-focusable-input" error but my situation is different from the explained in the other post I could find there.
I have this error message duplicated first on a well pointed input, this input has no required attribute:
The code:
<fieldset>
<label>Total (montaje incl.)</label>
<input type="number" id="priceFinal" name="priceFinal"> €
</fieldset>
The error:
An invalid form control with name='priceFinal' is not focusable.
While the user is filling the form this field gets its value by a js script with jquery. The user type a size in another input, the script do its maths with the size value and then put the outcome in the 'priceFinal' input with the jquery function: .val()
In the browser we can see that the input is correctly filled and no errors are displayed at that time. And with the 'novalidate' solution everything goes fine, so it couldn't be responsible for the nofocusable error, I think.
Then I got the same error with an input with no name which I didn't write and doesn't exist in my DOM:
An invalid form control with name='' is not focusable.
This is weird because the only input without name in my form is the type:submit one
<input type="submit" class="btn btn-default" value="Ver presupuesto" />
I have a few required fields but I've always checked that their are all filled when I send the form. I paste it just in case it could help:
<fieldset>
<input type="text" id="clientName" name="clientName" placeholder="Nombre y apellidos" class="cInput" required >
<input type="text" id="client_ID" name="client_ID" required placeholder="CIF / NIF / DNI" class="cInput">
</fieldset>
<fieldset>
<input type="text" id="client_add" name="client_add" placeholder="Dirección de facturación" class="addInput" required >
</fieldset>
<fieldset>
<input type="text" id="client_ph" name="client_ph" placeholder="Teléfono" class="cInput" required>
<input type="email" id="client_mail" name="client_mail" placeholder="Email" class="cInput" required>
</fieldset>
The novalidate solution clears the error but it doesn't fix it, I mean there must be a way to solve it with no hacks.
Any one have any idea of what's might going on?
Thanks
I had the same problem, and everyone was blaming to the poor hidden inputs been required, but seems like a bug having your required field inside a fieldset.
Chrome tries to focus (for some unknown reason) your fieldset instead of your required input.
This bug is present only in chrome I tested in version 43.0.2357.124 m.
Doesn't happen in firefox.
Example (very simple).
<form>
<fieldset name="mybug">
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
An invalid form control with name='mybug' is not focusable.
The bug is hard to spot because usually fieldsets don't have a name so name='' is a WTF! but slice piece by piece the form until I found the culprid.
If you get your required input from the fieldset the error is gone.
<form>
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<fieldset name="mybug">
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
I would report it but I don't know where is the chrome community for bugs.
Thanks to this post, I saw that my problem also rested with Chrome trying to focus on my fieldsets, instead of the input field.
To get a better response from the console:
Assign every DOM element a new name
Set every input & select style.display to 'block'
Changed the type of input[type="hidden"] elements to 'text'
function cleanInputs(){
var inputs = document.getElementsByTagName( 'input' ),
selects = document.getElementsByTagName( 'select' ),
all = document.getElementsByTagName( '*' );
for( var i=0, x=all.length; i<x; i++ ){
all[i].setAttribute( 'name', i + '_test' );
}
for( var i=0, x=selects.length; i<x; i++ ){
selects[i].style.display = 'block';
}
for( var i=0, x=inputs.length; i<x; i++ ){
if( inputs[i].getAttribute( 'type' ) === 'hidden' ){
inputs[i].setAttribute( 'type', 'text' );
}
inputs[i].style.display = 'block';
}
return true;
}
In the console, I ran cleanInputs() and then submitted the form.
The result, from the console, was:
An invalid form control with name='28_test' is not focusable.
An invalid form control with name='103_test' is not focusable.
Then, switching over to the Web Developer "Elements" view, I was able to find "28_test" and "103_test" (both fieldsets) -- confirming that my problem was a required input field, nested inside a fieldset.
While I was writting the question I realized one thing: the value the script was putting into the 'priceFinal' field sometimes was a decimal number.
In this case the solution was to write the step attribute for this input:
... step="any" ...
Step on w3s
So this 'nofocusable' bug is not only a required and hidden fields issue, it's also generated by format conflicts.
Nach gave me the best pointer... (y) I also had a input type="number" with step="0.1" and the console shows me this error while validating: An invalid form control with name='' is not focusable.
remove the step="0.1" on the element and now the form can be validated
I had the same issue so I removed required="required" from the troublesome fields.
If you get the error when jQuery function is executed, try to put "return false" on your function, or function(e) { e.preventDefault(); ... }
i had this issue once. to fix it, add
novalidate
as an attribute to the form. e.g
<form action="" novalidate>
....
</form>
In my case, the input element did not have a required attribute but it was hidden. and the problem was while it was hidden, it had a value in it. I guess if an input field is hidden it shouldn't have a value too, aside required attribute.
When I remove the value through my javascript code, everything works fine.
Element is hidden, No required Attribute, No value. Worked
Here is the solution....
<form>
<input type="text" ng-show="displayCondition" ng-required="displayCondition"/>
</form>
Many people do not realize that passing false into ng-required disables the directive.
Currently the HTML5 <datalist> element is supported in most major browsers (except Safari) and seems like an interesting way to add suggestions to an input.
However, there seem to be some discrepancies between the implementation of the value attribute and the inner text on the <option>. For example:
<input list="answers" name="answer">
<datalist id="answers">
<option value="42">The answer</option>
</datalist>
This is handled differently by different browsers:
Chrome and Opera:
FireFox and IE 11:
After selecting one, the input is filled with the value and not the inner text. I only want the user to see the text ("The answer") in the dropdown and in the input, but pass the value 42 on submit, like a select would.
How can I make all browsers have the dropdown list show the labels (inner text) of the <option>s, but send the value attribute when the form is submitted?
Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select would be a better choice.
To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:
To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value with the value of the datalist option instead of the innerText.
The following code then checks for an option with that value, pushes that into the hidden field and replaces the input.value with the innerText.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText says, but the unique id from option.value is available upon form submit.
Demo jsFiddle
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
to get text() instead of val() try:
$("#datalistid option[value='" + $('#inputid').val() + "']").text();
Using PHP i've found a quite simple way to do this. Guys, Just Use something like this
<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
<datalist id="customers">
<?php
$querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
$resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());
while ($row_this = mysqli_fetch_array($resultSnamex)) {
echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
<input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
}
?>
</datalist>
The Code Above lets the form carry the id of the option also selected.