I have a form looking like:
<form>
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
<input type"checkbox" name="checked[(unique_id)]">
</form>
The number of checkboxes will variate from time to time so when processing this data with PHP I have to loop the _POST['checked'] array.
My problem is that I want to take actions both when a checkbox is checked and when it's not. But only the the checked checkboxes will be added to the _POST['checked'] array.
<form>
<input type="checkbox" key="1"/>
<input type="hidden" name="checked[1]" value="false">
<input type="checkbox" key="2"/>
<input type="hidden" name="checked[2]" value="false">
<input type="checkbox" key="3"/>
<input type="hidden" name="checked[3]" value="false">
<input type="checkbox" key="4"/>
<input type="hidden" name="checked[4]" value="false">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('[key]').change(function () {
var key = $(this).attr('key');
$($('[name="checked[' + key + ']"]')).val($(this).is(':checked') ? 'true' : 'false');
});
});
</script>
here is what i'm doing
i'm using two inputs one is checkbox without name so it won't be sent to php
, the other is hidden won't be shown to the user but it is what will be sent to php
then with jquery when the user check the box jquery change the value of the hidden input to true and when uncheck it change the value to false
so the value will always be send to the php with value true or false as string
you can change the value you want to send to php by changing this
.is(':checked')?'true':'false')
to something like that .is(':checked')?1:0) to send 1 and 0 instead of true and false
another solution is rybo111 solution
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
it will send the two options but if the checkbox is checked it will override the first option
but it is not reliable 100% and it will send more data to the server
read more about that in POSTing Form Fields with same Name Attribute
so if you want to use simple solution without js use the "html only"
if you want 100% reliable solution use the "js"
Here's a technique I've seen before:
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
The reason this works is because when values with the same name are sent more than once, only the last value is accepted.
In my opinion, a better way is to simply use isset($_POST['...']) or in_array($_POST['...']).
Add value="true" to each checkbox input element.
And change your PHP code to :
$checked_arr = [];
foreach($_POST["checked"] as $checked){
if($checked == "true"){
// do what you want to do
}
}
Another Solution is server-side solution that I think is too fast and easy.
client side:
Just use fresh HTML :
<input type="checkbox" name="checked1" value="value_checked" ... />
server side:
make global function like this:
function getVal(&$var, $default = '') {
if (!isset($var) || empty($var) || is_null($var))
$var = $default;
return $var;
}
then use where you want to read some value that you don't know is set or not.
like this:
$checked_value = getVal($_POST["checked1"],false);
or
$checked_value = getVal($_POST["checked1"],"value_not_checked");
I hope useful to another one.
This is best approach according to my experience
<input type="hidden" name="check" value="false">
<input type="checkbox" name="check" value="true">
Related
I created checkboxes in form using javascript:
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
<input type="checkbox" name="is_ok[]" />
When I check 1st and 3rd checkbox and submit the form, Input::get("is_ok") returns me:
['on', 'on']
Is there any way to get value as ['on', null, 'on'] or ['on', 'off', 'on']?
Thanks in advance.
Hey assign some values to checkboxes like user_id, product_id etc what ever in your application.
E.g. View
<input type="checkbox" name="is_ok[]" value="1" />
<input type="checkbox" name="is_ok[]" value="2" />
<input type="checkbox" name="is_ok[]" value="3" />
E.g. Controller
<?php
if(isset($_POST['is_ok'])){
if (is_array($_POST['is_ok'])) {
foreach($_POST['is_ok'] as $value){
echo $value;
}
} else {
$value = $_POST['is_ok'];
echo $value;
}
}
?>
You will get array of selected checkbox.
Hope it helps..
I think I have a "good" solution to this (kind of).
<input type="checkbox" name="is_ok[0]" />
<input type="checkbox" name="is_ok[1]" />
<input type="checkbox" name="is_ok[2]" />
(Forced indices here)
In the request:
$array = \Request::get("is_ok") + array_fill(0,3,0);
ksort($array);
This will ensure that (a) The checkbox indices are maintained as expected. (b) the gaps are filled when the request is received.
It's sloppy but may work.
IMHO this is the best practice:
In your migration set that db table field to boolean and default 0
$table->boolean->('is_ok')->default(0);
{!! Form::checkbox('is_ok[]', false, isset($model->checkbox) ? : 0) !!}
and if you are not using laravel collective for forms then you can use vanilla php
<input type="checkbox" name="is_ok[]" value="<?php isset($model->checkbox) ? : 0; ?>" />
My solution is this for laravel 5
$request->get('is_ok[]');
Though it might not be best practice, here is what I did first of all I send id of a specific model as a value.
<input type="checkbox" id="verify" name="is_varified[]" value="{{$bank->id}}" {{$bank->is_varified == 1 ? 'checked':''}}>
And in controller I added two query to update the field.
//handaling the issue of checkbox
Bank::where("user_id",$user->id)->whereIn('id',$request->is_varified)->update(['is_varified'=> 1]);
Bank::where("user_id",$user->id)->whereNotIn('id',$request->is_varified)->update(['is_varified'=> 0]);
So i have this line of code that will repeat different times in a form.
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
<input type="checkbox" name="checkbox[]" /> !checked
<input type="checkbox" name="checkbox[]" /> !unchecked
The !checked show that the checkbox was checked and the !unchecked shows that the checkbox was not checked.
How can i create a php array to get values of checked and unchecked checkboxes in order like this :
array( 0 => checked, 1 => unchecked, 2 => checked, 3 => unchecked );
Momentarily i can get just the checked value with $_POST["checkbox"] but i cannot get the unchecked value.
First of all you need to put a value to your checkboxes:
<input type="checkbox" name="checkbox[]" value="checkboxNchecked" /> !checked
You can't really distinguish your checkboxes otherwise.
Then: Your checkboxes will either return a value if they are checked or will be ignored when they are unchecked. You will not get a NULL, FALSE or other value. It will simply not be transfered via POST/GET to your php script as if it wasn't in yout HTML code. This covers the topic: Does <input type="checkbox" /> only post data if it's checked?
If you know how many checkboxes are around and what they are called - no problemo señor - but if you don't, you'll need to find a way around. If you tell us what the nature of your checkboxes are, we can help you find a tailored solution.
you can use jquery and ajax. In your submit event get all values from the form and submit it by ajax. you can get unchecked value in jquery like this:
$("input:checkbox:not(:checked)")
or
if ($('#idOfYourCheckBox:checked').length > 0) {
//its checked
}
else {
//not checked
}
This will print only checked fields, because unchecked ones are not sent to server.
You will have to do some javascript and hidden field tricks.
Take a look here
Post the checkboxes that are unchecked
<input type="checkbox" name="checkbox[n1]" /> !checked
<input type="checkbox" name="checkbox[n2]" /> !unchecked
<input type="checkbox" name="checkbox[n3]" /> !checked
<input type="checkbox" name="checkbox[n4]" /> !sdsk
foreach($_POST['checkbox'] as $key => $value){
$checkbox[$key] = 'checked';
}
print_r($checkbox); // your new array
Solved:
Declaration of form...
<form id="form1" name="form1" method="post" action="xx.php" onSubmit="set_hidden_value()">
<input name="arrayofchecks" type="hidden" value="toset" />
...
OnSubmit:
function set_hidden_value()
{
var checkstring = "";
for (var i=0; i < $('#checkbox').length; i++)
{
if ($('#checkbox')[i].checked)
{
checkstring = checkstring + "1";
}
else
{
checkstring = checkstring + "0";
}
}
$('#arrayofchecks').val(checkstring);
And the result is a string with values checked and unchecked (1 and 0)...
In my case, i use ajax for intercept submit and do set_hidden_value here...
If you are using a server side language like PHP, there is an easier method than using hidden fields to supply default or writing javascript (both may fail if the user's device/browser doesn't support that method).
<input type="checkbox" value="choice1" name="checkbox[]" />
<input type="checkbox" value="choice2" name="checkbox[]" />
<input type="checkbox" value="choice3" name="checkbox[]" />
This method doesn't return unchecked items, but it specifically identifies which items were checked. Otherwise, if the checkboxes all have the same value, all you get is one, two or 3 values repeated with no idea which item was checked. However, assuming choice2 was checked with the above method, it's pretty easy then to figure out that item 1 and 3 therefore were not checked.
Please check below code.
$("button").click(function () {
var i=0;
var cbox=[];
$("input[name='cbox']").each(function () {
if($(this).is(':checked')) {
cbox[i++] = $(this).val();
}else{
cbox[i++] = "unchecked";
}
});
console.log(cbox);
i = 0;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<input type="checkbox" value="checked" name="cbox">
<button>Click</button>
I have this:
<form method="post" id="kl" action="step2.php">
<input type="radio" name="rubrik" value="bussines"></input>
<input type="radio" name"rubrik" value="private"></input>
<input type="image" value="submit" src="/images/submit.png" alt="Submit" />
</form>
What i bassicaly want is: When the second radio button is checked, to submit the form to step2a.php, a different file. How can i do this? Jquery, Javascript, php?
You could do this with JavaScript (bind a submit listener that checks the value of the radio button and then sets the action property of the form), but it would be simpler and more reliable to do something (server side) along the lines of:
<form ... action="step-selector.php">
and
<?php
if (isset($_POST['rubrik']) && $_POST['rubrik'] == 'bussines') {
include('step2.php');
} elseif (isset($_POST['rubrik']) && $_POST['rubrik'] == 'private') {
include('step2a.php');
} else {
include('error-state.php');
}
?>
you can do this by modifying the Form into:
<form method="post" id="kl" action="step2.php">
<input type="radio" class="radio" rel="step2.php" name="rubrik" value="bussines"></input>
<input type="radio" class="radio" rel="step2a.php" name"rubrik" value="private"></input>
<input type="image" value="submit" src="/images/submit.png" alt="Submit" />
</form>
I added rel attribute to radio buttons. each has a value of the url. I also added a class to get the element with jQuery.
Now, you will need some Javascript, i will use jQuery code:
$('.radio').click(function (){
rad = $(this);
radRel = rad.attr('rel');
$('form#kl').attr('action', radRel);
});
There are multiple ways of doing it, depending on what you want exactly.
Check this one out, it might help you get there; Radio Button to open pages
You can use form.submit() as onclick-handler (not onchange) and change the action, too.
<input type="radio" name"rubrik" value="private" onclick="this.parentNode.action='yourOtherFile.php'; this.parentNode.submit()"></input>
I am modifying a php login form, adding javascript check form function to it. I wish when users tick the checkbox, the form is true, and when the checkbox is empty, the form becomes false. the codes are like these:-
//the javascript
function check_sli(form,mark,edit){
if(mark==1 || mark=="all"){
if(form.terms.value==""){
sli_check_terms.innerHTML="Please read the terms and conditions first!";
sli_check_terms.style.height="auto";
return false;
}else{
sli_check_terms.innerHTML="";
sli_check_terms.style.display = "none";
}
}
}
//the form
<form name="form_sli" id = "form_sli" ACTION="<?php echo $loginFormAction1; ?>" METHOD="POST" onSubmit="return check_sli(form_sli,'all')">
<input type="text" name="login"/><br>
<input type="password" name="password"/><br>
<input name="terms" type="checkbox" id="terms" checked="checked" onBlur="check_sli(form_sli,1)">I have read the terms and conditions<br><div id="sli_check_terms" class="right"></div>
<input type="submit" name="button" id="button" value="Login" />
</form>
The above codes works normal for textfields, such as when the textfield is empty, the innerHTML pops up. However, when using checkbox, I don't know the checked and unchecked value, is it 1 vs 0, or !=="" vs ==""??? and shall I use onBlur or onSubmit???
How shall it modify the scripts so that it works for checkbox as well? thanksalot!
checkboxes use .checked in the dom, which is a bool.
if (form.terms.checked) {
... it's checked ...
}
Instead of if(form.terms.value==""), do this if(form.terms.checked==false)
I know how to it with text inputs. I can easily put a php script in its value, but doing it with input groups seems different. How can I mantain the values of group inputs if the submission of the form fails?
To re-mark a checkbox or radio button as checked, you use this code:
<input type="checkbox" name="foo" id="foo" checked="checked"/>
The key is checked="checked".
If you are using groups of checkboxes, make sure the name of the field ends with brackets [], like this:
<input type="checkbox" name="foo[]" id="foo_1" value="1" checked="checked"/>
<input type="checkbox" name="foo[]" id="foo_2" value="2" checked="checked"/>
Then your $_REQUEST['foo'] variable will automatically be an array of checked values. You can use in_array to see if a particular checkbox was checked.
Update based on comment
Here's how I would set it:
<input type="checkbox" name="foo[]" id="foo_1" value="1" <?= (isset($_POST['foo'] && in_array('1', $_POST['foo'])) ? 'check="checked"' : '' ?>/>
For single items (like radios), use this:
<input type="radio" name="foo" id="foo" value="1" <?= isset($_POST['radio]) ? 'check="checked"' : '' ?>/>
Hope that helps.
Update 2:
Also, make sure you escape user input! Your example should look like this:
<input type="text" name="username" value="<?php if(isset($_POST['username']) echo htmlspecialchars($_POST['username']);?>">
Always assume the user is trying to hack your system, always escape user input!
Print the " checked" attribute for radio buttons and checkbox input tags, or the " selected" attribute for dropdown option tags.