Laravel Blade - How to make checkbox stay checked after submit - html

I want to create a feature to filter data. I use the checkbox to do this.
But I want when the checkbox is selected and then the user submits to filter the data, the previously selected checkbox remains selected.
i tried to do it like this but it didn't work
<input type="checkbox" id="ac" name="ac" value="ac" #if(old('ac')) checked #endif>
my form method to submit this is GET.

old() helper function is only for saved flash session data. Without saved it on flash session you can not retrieve it. An example to save flash data for old() function
request()->flashOnly(['ac']);
or
return redirect('form')->withInput();
If you use GET method and no redirection after submit you can do it using request() helper function. Like this:
<input type="checkbox" id="ac" name="ac" value="ac" #if(request()->ac) checked #endif>

For the submitting form using POST method with multiple checkboxes,
#foreach ($categories as $index => $category)
<div class="form-check form-check-inline">
<input type="checkbox" name="type[]"
value="{{ $category->id }}"
{{ (is_array(old('type')) && in_array($index + 1, old('type'))) ? 'checked' : '' }}
class="form-check-input #error('type') is-invalid #enderror"
id="type_{{$category->id}}">
<label class="form-check-label" for="type_{{$category->id}}">
{{ $category->name }}
</label>
</div>
#endforeach

This worked form me:
<input name="mail" type="hidden" value="0" >
<input name="mail" type="checkbox" value="1"#if(old('mail')) checked #endif>
controller:
$request->validate([
'mail' => 'required',
]);
Contact::create($request->all());

Related

Multiple values in radio input within form with vanilla HTML

I am aiming to create a form to handle disabled JavaScript experience for a small component on my website. Currently I have the following form:
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
...other radio options
<input type="submit" value="Submit" />
</form>
Clicking on either of the radio options and then on the submit button will result in:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity
option 2: https://mywebsite.com/somedirectory/?someParam=veggie
How can I add another value for each of the radio options? Say I would like to pass someOtherParam which is unique for each option and I would like to get this as output for my options:
option 1: https://mywebsite.com/somedirectory/?someParam=fruity&someOtherParam=apple
option 2: https://mywebsite.com/somedirectory/?someParam=veggie&someOtherParam=pepper
What I have tried is:
<input type="radio" id="uid1" name="someParam" value="fruity&someOtherParam=apple" />
<input type="radio" id="uid2" name="someParam" value="veggie&someOtherParam=pepper" />
However, the & symbol is converted to %26 inside the link and feels too hacky. Is there a better way to achieve this? Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
P.S. I am aiming for pure HTML experience with no Javascript involved. Is that possible?
I'm pretty sure this is not posible in modern browsers without the use of JS. Maybe on old browsers you could do some tricks with CSS and display:none because it used to not send fields with display:none, but nowdays that is not an option.
If you can allow Javascript, you can add a data attribute to each radio option and use it to populate an extra hidden input on change.
document.querySelectorAll('input[type=radio][name="someParam"]')
.forEach(radio => radio.addEventListener('change', (event) =>
document.getElementById('someOtherParam').value = event.target.dataset.extraValue
));
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="radio" id="uid1" name="someParam" value="fruity" data-extra-value="apple" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" data-extra-value="pepper" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="someOtherParam" name="someOtherParam">
<input type="submit" value="Submit" />
</form>
To add another radio group independent from others, use a distinct name property. For example, to add a second parameter called someOtherParam to the request, create a radio group with name="someOtherParam":
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
And add their correspondent labels.
Also, is there a way to make sure the Submit button is only enabled once a radio option is selected?
You can add the required attribute to prevent the browser to send the form before all the inputs have a value.
Without javascript, what you're describing cannot be done.
What you could do, as other posters have suggested is:
Create radio buttons for the list of options that are possible for each category (fruits / vegetables etc)
<input type="radio" id="uid3" name="someOtherParam" value="apple" />
<input type="radio" id="uid4" name="someOtherParam" value="pepper" />
When processing the input on your server side code, check if you have received a value or not. If not, you can choose a default option (apple or whatever). On your page you can mention what the default option would be in case they don't make a selection.
You could make some of the input required as suggested, but you would still have to make check on the server side that the input has been received, since the required attribute is just a suggestion to users browsers - it won't stop a malicious persons from making a request without that parameter by running a script etc.
To submit extra information to the server, you can use a hidden input type and change value as per your needs using javascript.
HTML code
<form method="GET" action="">
<input type="radio" id="uid1" name="someParam" value="fruity" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" value="veggie" />
<label for="uid2">Vegetable</label>
<input type="hidden" id="uid3" name="someOtherParam" value="" readonly required />
<input type="submit" value="Submit" onclick="onSubmit()" />
</form>
Javascript code
function onSubmit () {
let fruityRadio = document.getElementById( 'uid1' );
let veggieRadio = document.getElementById( 'uid2' );
if ( fruityRadio.checked ) {
document.getElementById( 'uid3' ).value = 'apple';
} else if ( veggieRadio.checked ) {
document.getElementById( 'uid3' ).value = 'pepper';
}
}
Easy, double up the value with a deliminator between every extra value:
HTML
<div>
<label for="uid1">
<input id="uid1" name="fruit1" type="radio" value="apple:orange" />
Fruit, Apple + Orange
</label>
</div>
<div>
<label for="uid2">
<input id="uid2" name="fruit1" type="radio" value="apple:cherry:lime" />
Fruit, Apple + Cherry + Lime
</label>
</div>
node.js
I'm not sure how node.js handles what PHP refers simply as $_POST['name_attribute_value_here'] though I do know you simply want to use .split(':') to get the two or more values from that single form. If you want more options per radio button just append a deliminator (it doesn't have to be :) between each value.
Both of those radio options have the name "fruit1" so the user can't choose both.
No JavaScript is necessary.
A minor adaptation on the server.
Extra values will obviously not appear to the server if the user doesn't select that radio form field.
Arrays
If you want to set your own key/values then just add a second deliminator:
<input name="fruit1" value="fruit:apple,fruit:lime,color:purple,planet:Earth" />
Then at the server use [whatever].split(',') to get the pairs and iterate in a loop to get each key/value. You could create an entire crazy multi-dimensional array if you really wanted to.
I hope this helps, feel free to comment if you need any further clarification.
Generate form:
const data = [
{ name: 'apple', type:"fruity" },
{ name: 'pepper', type:"veggie"}
]
const form = document.querySelector('form');
const uid = document.querySelector('#uid')
createOptions(data);
function createOptions(data){
data.forEach((e, index) => {
const f = document.createDocumentFragment();
const l = document.createElement('label');
const i = document.createElement('input');
l.setAttribute('for', `uid${index+1}`);
l.textContent=e.name;
i.setAttribute('type', `radio`);
i.setAttribute('for', `uid${index+1}`);
i.setAttribute('name', 'someOtherParam');
i.setAttribute('value', e.name);
i.dataset.otype = e.type;
f.appendChild(l);
f.appendChild(i);
form.insertBefore(f, uid);
i.addEventListener('change', onselectChange, false);
})
}
function onselectChange(event) {
uid.value = event.target.dataset.otype;
}
<form method="GET" action="https://mywebsite.com/somedirectory/">
<input type="text" id="uid" name="someParam"
style="width:0; visibility: hidden;">
<input type="submit" value="Submit" />
</form>
I can't think another way of doing this using less code, the following achieves your desired result:
<form name="form" method="GET" action="">
<input type="radio" id="uid1" name="someParam" required value="fruity" onchange="document.form.someOtherParam.value = 'apple'" />
<label for="uid1">Fruit</label>
<input type="radio" id="uid2" name="someParam" required value="veggie" onchange="document.form.someOtherParam.value = 'pepper'" />
<label for="uid2">Vegetable</label>
<input type="hidden" name="someOtherParam" value=""/>
<input type="submit" value="Submit"/>
</form>
There's only 3 changes to your example:
Add a name to the form, then add inline attributes required and onchange to each radio, finally add an input[type=hidden] to include the extra param. The first change is meant so you'll not need document.getElementById later, the second so the form won't be empty submitted and also update the hidden desired value.

Can a <FORM> submit radio-button's <LABEL> as VALUE?

We currently use the following syntax for radio buttons:
<input type="radio" id="opt1" name="option" value="opt1" required/>
<label for="opt1">Description of Option One</label>
<input type="radio" id="opt2" name="option" value="opt2" required/>
<label for="opt2">Description of Option Two</label>
The query-processing script receives the string "opt1", which it then needs to convert to the full-text description of the option. In PHP-speak, I get:
$_POST['option'] => "opt1"
I'd like to save that step and have the full text of the description to be submitted as the value:
$_POST['option'] => "Description of Option One"
Can this be done with HTML alone -- without resorting to JavaScript-rewriting hacks and without duplicating the description text in the HTML? Thanks!
Unfortunately not.
If you have control over the form, the best solution is to use the description for the value:
<input type="radio" id="opt1" name="option" value="Description of Option One" required/>
<label for="opt1">Description of Option One</label>
<input type="radio" id="opt2" name="option" value="Description of Option Two" required/>
<label for="opt2">Description of Option Two</label>
If you don't have control over the form, then javascript is your only solution, you could use a function like the below (either inside an onload event for the page or an onsubmit event on the form:
function radioUpdate() {
document.querySelectorAll('radio').forEach(function(input) {
input.value = document.querySelector('label[for="' + input.id + '"]').text();
});
};
No, it can't.
Consider generating the HTML from your server side code in the first place. You could write a PHP function that takes the label/value as a single argument.

Getting checkboxes ticked based on the value extracted from database for edit form

I have my values stored in database as follows:
I am able to get all the values in my form from database for editing purpose as follows:But I am not able to get checkboxes ticked based on the values that I have stored in my database i.e. if I have MBBS and BDS in my database, i would like to have MBBS and BDS checkboxes ticked in my edit form.
For single value in course column, i was able to achieve single tick as follows:
<div class="form-group">
<label for='degree'>Degree : </label>
<label class="checkbox-inline">
<input type="checkbox" value="MBBS" id="course" name="course"
#if($book->course == "MBBS")
{{"checked" }}
#endif
/>MBBS
</label>
<label class="checkbox-inline">
<input type="checkbox" value="BDS" id="course" name="course"
#if($book->course == "BDS")
{{"checked" }}
#endif
/>BDS
</label>
<label class="checkbox-inline">
<input type="checkbox" value="B.Pharma" id="course" name="course"
#if($book->course == "B.Pharma")
{{"checked" }}
#endif/>B.Pharma
</label>
</div>
How can i access the values in checkboxes of my edit form?
Your course seem to have comma separated value, so you need to explode it and cross check it.
Try this to get a match
#if(in_array("MBBS", explode(",", $book->course)))
{{"checked" }}
#endif

What data-calc-type means?

I have a question about type of button. What data-calc-type means in this code?
<label for="x">x: </label><input id="x" type="number" placeholder="0"/>
<label for="y">y: </label><input id="y" type="number" placeholder="0"/>
<label for="z">z: </label><input id="z" type="number" placeholder="0"/>
<div id="calculations">
<button data-calc-type="area">Pole</button>
<button data-calc-type="circuit">Obwód</button>
<button data-calc-type="volume">Objetość</button>
</div>
<p>Wynik: <span id="result"></span></p>
The data-* attribute is very neat. It let you store data in it so you can refer to it with your script.
Exemple: You have many buttons in your page. All buttons do different action. Instead of calling many function you could call one function that deal with data attribue and process data accordingly.
if ($('#button_ID').attr('data-*') == "this attribute"){ //do something}

Passing checkbox values to mysql database using Codeigniter

I'm using CodeIgniter and mySQL to build a checkbox form. The form contains 4 options; each option has only one checkbox; users can select any combination of the options. I want to do the following:
1 - For each checkbox, use a value of 1 (if unchecked) or 2 (if checked) and pass those values through to the database (each checkbox has its own field). Right now, whether checked or unchecked, the checkboxes are sending a value of 0 through to the database.
2 - Once users update their checkboxes, I'd like to update the database to reflect the new values. Right now, a new row is added for each update to the checkboxes.
What I've got so far is a form that submits the checkbox values to the database, a controller, and a model):
Form
<?php echo form_open('addFoo'); ?>
<input type="checkbox" name="foo1" value="" />
<input type="checkbox" name="foo2" value="" />
<input type="checkbox" name="foo3" value="" />
<input type="checkbox" name="foo4" value="" />
<?php echo form_submit('submit', 'Save Changes'); ?>
<?php echo form_close(); ?>
Controller
function addFoo()
{
if ($this->input->post('submit')) {
$id = $this->input->post('id');
$foo1 = $this->input->post('foo1');
$foo2 = $this->input->post('foo2');
$foo3 = $this->input->post('foo3');
$foo4 = $this->input->post ('foo4');
$this->load->model('foo_model');
$this->foo_model->addFoo($id, $foo1, $foo2, $foo3, $foo4);
}
}
Model
function addFoo($id, $foo1, $foo2, $foo3, $foo4) {
$data = array(
'id' => $id,
'foo1' => $foo1,
'foo2' => $foo2,
'foo3' => $foo3,
'foo4' => $foo4
);
$this->db->insert('foo_table', $data);
}
At your Controller :
if you want to insert new entry for all selected checkbox:
foreach($this->input->post('foo') as $r)
{
$data['fieldname']=$r;
$this->model_name->insert($data);
}
if you want to insert all selected checkbox values in different fields within single entry then,
foreach($this->input->post('foo') as $key=>$val)
{
$data['field'.$key]=$val;
}
$this->model_name->insert($data);
Well in reference to setting the values, a checkbox doesn't send anything if unchecked. To achieve what you want, you have to do this:
<input type="checkbox" name="foo[]" value="1" />
<input type="checkbox" name="foo[]" value="2" />
This will send a value regardless of whether the checkbox is checked or not.
use the different values for each checkbox and get the value of checkbox array and use this in your controller print_r($this->input->post('foo')); it will print the values that are selected by user
use like this
<?php
if (isset($_POST['submit'])){
print_r($_POST['foo']);
}
?>
<form action="" method="POST">
<input type="checkbox" name="foo[]" value="1">1<br>
<input type="checkbox" name="foo[]" value="2">2<br>
<input type="checkbox" name="foo[]" value="3">3<br>
<input type="checkbox" name="foo[]" value="4">4<br>
<input type="submit" value="submit" name="submit">
</form>