How insert a form data to mysql when checkbox is checked? - mysql

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
}

Related

How do I remove a parameter with blank response from URL generated by the <form> tag?

I am writing a search box in HTML that takes the user input and append it to the URL as a parameter. The code of the form looks like this.
<form name="form" action="" method="get">
<input type="text" name="id" id="idresponse">
<input type="submit" value="Submit">
</form>
This will bring the user from example.com/test.html to example.com/test.html?id=12345678 assuming they entered 12345678 at the text box.
However, if the user inputted nothing and clicked Submit, they will be brought to example.com/test.html?id=, which I don't want. How can I modify the code so that the form knows that a certain field is left blank and do not send the parameter with the URL? In this case, the desired URL would be example.com/test.html.
edit 20210405 2057 changed the id of the input from idresposne to idresponse to avoid confusion
The so-called URL parameters is the querystring of the URL.
The following code does not use jQuery, but achieves a similar effect. (written by RobG)
<form name="form" onsubmit="disableEmptyInputs(this)" action="" method="get">
<input type="text" name="id" id="idresponse">
<input type="submit" value="Submit">
</form>
<script>
function disableEmptyInputs(form) {
var controls = form.elements;
for (var i=0, iLen=controls.length; i<iLen; i++) {
if (controls[i].value == '') controls[i].disabled = true;
}
}
<script>
This will remove all the parameters but the ? will still trail the URL. i.e. the URL will be example.com/test.html? instead. However, this does not matter because they both point to the same address.
Refer to these links (kindly provided by Progman) for other ways of doing this, including using jQuery.
Delete empty values from form's params before submitting it
Delete empty values from form's params before submitting it
How can I remove empty fields from my form in the querystring?
Thanks.

How to switch between to value from switch input?

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

Validation failed due to manually inserted value

Value of filename is being manually inserted using this
<input type="file" ngf-select ng-model="file" name="file" id="file" onchange="document.getElementById('fileName').value = this.value.split('\\').pop().split('/').pop()" required>
Filename is being injected into fileName field using the file a user chooses. Validation fails as it treats that field as still being empty until I at least insert one more character. What can I do to fix that?
This is the validation part
<p ng-show="fileNameForm.fileNameInput.$error.required && fileNameForm.fileNameInput.$touched" class="help-block">File name is required.</p>
And the actual text field
<input name="fileNameInput" class="form-control" type="text" id="fileName" ng-model="document.fileName" ng-maxlength="255" required>
on change will not be evaluated if the model is changed programmatically and not by a change to the input value
you can use $scope.$watch to detect changes on ng-model
$scope.$watch('document.fileName', function(newValue, oldValue) {
//if(newValue not valid)
// display validation error
});

In AngularJS How to toggle between 2 checkboxes and get only 1 value

In AngularJS; How do I toggle between two checkboxes and get only one value
<td >
<input type="checkbox" value="{{person.person_ID}}">{{person.home_address}}
</td>
<td >
<input type="checkbox" value="{{person.person_ID}}">{{person.office_address}}
</td>
According to the requirement I have list of persons in that every person has two
columns home_address and office_address, I want to toggle between addresses and get only 1
value like if person.home_address is checked than office_address should be unchecked and vice versa, and I want to get only 1 address like "person.person_ID":home_address
You can use ng-model to bind to a value in your person instance using the following html. (A fiddle is available)
<input type="checkbox"
ng-model="person.option"
value="{{person.person_ID}}"
ng-true-value="'home'"
ng-false-value="'none'">{{person.home_address}}
<input type="checkbox"
ng-model="person.option"
value="{{person.person_ID}}"
ng-true-value="'office'"
ng-false-value="'none'">{{person.office_address}}
here the checkboxes binds to the same variable person.option which is set depending on the value of the checkbox to the expression in ng-true-value and ng-false-value. By setting these to the some value other than that of the other we can either select none, or only one.
In your controller you can simply check person.option to get what checkbox is selected.
if (person.option === 'home') { }
else if (person.option === 'office') { }

Do checkbox inputs only post data if they're checked?

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