how to make radio buttons behave in a mutually exclusive way - php

I was to trying to update my checkbox value based on checked..But the problem I'm facing is i can't uncheck the old checkbox checked ..So when i click on the new checkbox the old one should be uncheck...I have used laravel platform where table header comes from database and from database the old checkbox value came..
here is my blade view :
<table class="table">
<thead>
<tr>
<th>SL No</th>
<th>Name</th>
#foreach($roles as $row)
<th>{{$row->label}}</th>
#endforeach
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($users as $user)
#foreach($user->roles as $row)
<tr>
<td>{{$i}}</td>
<td>{{$user->name}}</td>
#foreach($roles as $role)
<td>
#if($role->role == $row->role)
<input type="checkbox" class="myCheckbox" checked="" >
#else
<input type="checkbox" class="myCheckbox">
#endif
</td>
#endforeach
</tr>
<?php $i++; ?>
#endforeach
#endforeach
</tbody>
</table>
Here is the javascript i used for check only one checkbox .
$('.myCheckbox').click(function() {
$(this).siblings('input:checkbox').prop('checked', false);
});
anybody could help me to find out the solution please?

Either use radio buttons, or iterate over all checkboxes setting the checked value to false and only checking the just clicked checkbox.
Here is an example.
var container = document.querySelector('.container');
container.addEventListener('click', function(evt) {
[].slice.call(this.children).forEach(function(input) {
input.checked = false;
})
evt.target.checked = true;
})
<div class="container">
<input type="checkbox"> Foo
<input type="checkbox"> Bar
<input type="checkbox"> Baz
</div>

Related

Update status in database using checkbox - Laravel

The project can have different statuses. With the checkbox, I am trying to switch the status of the project from requested (1) to accepted (2). If the checkbox is unchecked the status is 1, checked it's 2.
When I check the checkbox I got a 419 but this is normally related to the token but I added a #csfr field. Why is the status not changed in the database?
Thanks for any help.
index.blade.php (summary of all the projects)
#foreach ($projects as $project)
<tbody>
<tr>
<form action="/projects/plan" method="post" id="statusForm">
#csrf
<input name="id" type="hidden" value="{{$project->id}}">
<td>
<input type="hidden" value="{{$project->status}}" name="status">
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="{{$project->status}}" type="checkbox" name="status"
onchange="document.getElementById('statusForm').submit()"
>
</td>
</form>
<td>{{$project->applicant_name}}</td>
<td>{{$project->project_name}}</td>
<td>Project Details</td>
</tr>
</tbody>
#endforeach
Project.php (functions to update status)
const STATUS_requested = 1;
const STATUS_ACCEPTED = 2;
public function updateStatus( $status )
{
$this->update([
'status' => $status
]);
$this->refresh();
return $this;
}
public function projectAccept() {
return $this->updateStatus( self::STATUS_ACCEPTED );
}
ProjectsController.php (dd('hello') is not printed it seems like data is not sent to this resource)
public function plan(Request $request)
{
dd('hello');
Event::find($request->id)->projectAccept();
return Project::STATUS_ACCEPTED;
}
web.php
// Update status project
Route::post('/projects/plan', 'ProjectsController#plan');
First, you cant select by ID document.getElementById('statusForm').submit() when you have multiple DOMS with the same ID.
change your loop to something like this
#foreach ($projects as $project)
<tbody>
<tr>
<td>
<form action="/projects/plan" method="post" id="statusForm{{$project->id}}">
#csrf
<input name="id" type="hidden" value="{{$project->id}}">
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="2" type="checkbox" name="status"
onchange="document.getElementById('statusForm{{$project->id}}').submit()"
>
</form>
</td>
<td>{{$project->applicant_name}}</td>
<td>{{$project->project_name}}</td>
<td>Project Details</td>
</tr>
</tbody>
#endforeach
Now, a checkbox will only be sent in a form when it is checked, so no need for a variable value for that input
<input {{isset($project['status']) && $project['status'] == '2' ? 'checked' : ''}}
value="2" type="checkbox" name="status"
onchange="document.getElementById('statusForm{{$project->id}}').submit()"
>
Finally, when you recover the input status, set a default value for the unchecked one (you can remove the hidden input with this one). Or as you did, set a hidden input with the original value to be sent every time. Both solution are perfect.
public function plan(Request $request)
{
$status = $request->input('status', Project::STATUS_requested);
Event::find($request->id)->projectAccept();
return Project::STATUS_ACCEPTED;
}
That way if it is checked it will be 2 (in the request) and if not, it will be 1 from the default value.

Laravel Inserting Data Only the Last List or Data

I want to insert the data specifically look at my page.
When I set time the data will be inserted. But what I have right now is the data that is inserted is the very last data on this table which is January-31-2019 how can I fix it so when I insert data, the data will insert any of the data that is list on the table.
Controller
public function insertSchedule(Request $request)
{
$employeeTimeSet = new Schedule;
$employeeTimeSet->employee_no = $request->input('hidEmployeeno');
$employeeTimeSet->last_name = $request->input('hidEmployeeLast');
$employeeTimeSet->first_name = $request->input('hidEmployeeFirst');
$employeeTimeSet->date_today = $request->input('dateToday');
$employeeTimeSet->time_in = $request->input('timeIn');
$employeeTimeSet->time_out = $request->input('timeOut');
$employeeTimeSet->save();
$notification = array(
'message' => 'Click PLAN TIME! Employee Time Set!',
'alert-type' => 'success'
);
return redirect()->back()->with($notification, 'Employee Time Set');
}
View
{!! Form::open(['action' => 'Admin\EmployeeFilemController#insertSchedule', 'method' => 'POST']) !!}
<div class="row">
<div class="form-group col-md-12">
<small>Employee No. and Name:</small>
<b><i> {{ $employee->employee_no }} : {{ $employee->last_name }}, {{ $employee->first_name }}</i></b>
<input type="hidden" name="hidEmployeeno" value='<?php echo $employee->employee_no ?>'>
<input type="hidden" name="hidEmployeeLast" value='<?php echo $employee->last_name ?>'>
<input type="hidden" name="hidEmployeeFirst" value='<?php echo $employee->first_name ?>'>
<hr>
</div>
</div>
#php
$today = today();
$dates = [];
for($i=1; $i < $today->daysInMonth + 1; ++$i) {
$dates[] = \Carbon\Carbon::createFromDate($today->year, $today->month, $i)->format('F-d-Y');
}
#endphp
<table class="table">
<thead>
<tr>
<th>DATE TODAY</th>
<th>TIME IN</th>
<th>TIME OUT</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
#foreach($dates as $date)
<tr>
<td><b>{{ $date }}</b></td>
<input type="hidden" name="dateToday" value="{{ $date }}">
<td><input type="time" name="timeIn" class="form-control col-md-10"></td>
<td><input type="time" name="timeOut" class="form-control col-md-10"></td>
<td> {{Form::button('<i class="fa fa-clock"> SET TIME</i>',['type' => 'submit','class' => 'btn btn-warning btn-sm', 'style'=>"display: inline-block;"])}}</td>
</tr>
#endforeach
</tbody>
</table>
{!! Form::close() !!}
The issue is that you are using one form with multiple inputs in it and there is no unique name to them. If you inspect the code, your form will have 31 inputs with name timeIn and 31 inputs with name timeOut.
When you submit the form, It picks the last timeIn and timeOut.
Two soluctions
Make multiple forms (put form tags in while loop, it will create 31 forms in the page)
Use ajax to send data to the server.
You need to use [] for your textbox names. Example : name[] and you need to use a loop to post it. Example - how to get post from same name textboxes in php
In Addition to the #Swaroop's Answer there is another option. You can make array of these fields in the same form and submit them. and at the server end, you will have to loop through posted array so that you can process them further.

How to pass php variable outside of while loop within same page

I have faced small problem regarding passing php variable outside of PHP loop. I have created table and form in same page. First table is displayed and the through edit link in form pop up dialog box appears. I want to pass dynamic ID to dialog box after click edit link. My page includes a php table and form.
PHP/HTML Table
<table>
<th>ID</th>
<th>Title</th>
<th>Edit</th>
<?php
$query="select * from video order by id desc";
$result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
while($row=$result->fetch_assoc()){
$id=$row['id'];
$heading=$row['heading'];
?>
<tr>
<td>
<?php echo $id ?>
</td>
<td>
<?php echo $heading ?>
</td>
<td>
Edit
</td>
</tr>
<?php } ?>
</table>
After this table, I want to display data in this form
PHP Form in dialog box
<div class="remodal" data-remodal-id="modal2" role="dialog" aria-labelledby="modal2Title" aria-describedby="modal2Desc">
<form action="" method="POST" enctype="multipart/form-data">
<table>
<tr>
<th>Video ID</th>
<td>
<input type="number" value="<?php echo $id?>" name="id" readonly></input>
</td>
</tr>
<tr>
<th>Video Title</th>
<td>
<input type="text" value="<?php echo $heading?>" name="title"></input>
</td>
</tr>
</table>
</form>
</div>
I know that while loop can't connect to popup dialog box form, so my code prints only data of first row. If I include whole code within while loop, my table structure become mess. Is there any idea to pass ID outside of while loop ? I tried using global variable method, but it doesn't work. Perhaps I can't properly use global variable. Thanks
In your while loop store values in to array like this:
<?php
$query="select * from video order by id desc";
$result=$con->query("SELECT * FROM video ORDER by id DESC") or die($con->error);
$array = [];
while($row=$result->fetch_assoc()){
$id=$row['id'];
$heading=$row['heading'];
$array[$id] = $heading;
?>
And in your html table like this :
<table>
<tr>
<th>Video ID</th>
<th>Video Title</th>
<?php foreach ($array as $key => $val){ ?>
<td>
<input type="number" value="<?php echo $key?>" name="id" readonly></input>
</td>
<td>
<input type="text" value="<?php echo $val?>" name="title"></input>
</td>
<?php } ?>
</tr>
</table>

Send and receive state of unknown number of checkboxes through html form

I have a MySql table and I would to be able to modify through a HTML form. The MySql table has columns like this:
id (int) | name (text) | option1 (boolean) | option2 (boolean)
The number of field options will grow over time and is not fixed, but always contains boolean data (0 or 1). The number of rows is not fixed as well.
I would like to modify the table with a html form which looks like this:
<form action="file.php" method="post">
<table style="width:100%">
<tr>
<th>Name</th>
<th>Option1</th>
<th>Option2</th>
</tr>
<tr>
<th>lili</th>
<th><input type="checkbox" name="lili_1"checked></th>
<th><input type="checkbox" name="lili_2"></th>
</tr>
<tr>
<th>thor</th>
<th><input type="checkbox" name="thor_1" checked></th>
<th><input type="checkbox" name="thor_2" checked></th>
</tr>
<tr>
<th>fred</th>
<th><input type="checkbox" name="fred_1" checked></th>
<th><input type="checkbox" name="fred_2" ></th>
</tr>
</table>
<button type="submit">Update</button>
</form>
Now it gets tricky. When I submit the form, on the server side I don't know how many columns/lines there are. I would like to update the whole database table (it's small), so I need to know the state of every checkbox for columns (option1, option2, ...) and rows (lili, thor, fred,...)
My idea is to name each checkbox based on the column and value of field "name". I would also need to send an array containing all the names and the columns (because I can only know the boxes that were checked, not the unckecked ones).
On server-side, I then need to recreate the matrix with the array of columns and names and put 1 where a checkbox was checked (through the name of the checkbox).
This seems to be a very error-prone and long to implement... to do such an simple task. Can someone points me to a smarter way to to that ?
Thank you
You can group checkboxes with name="thor[]" or name="lili[]" in php backend you can retrieve it by $_REQUEST['thor']. Remember it is an array. So you loop it by foreach($_REQUEST['thor'] as $thor){} check value by if($thor)
The solution is to add a bit of Javascript that will capture all of the field names and assign them to the value of a hidden field just before the form is submitted. That will provide you with all of the info you need for server side processing. Here is a working sample.
test.php
<html>
<head>
<title>test.php</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
var element = $(this);
var names = [];
element.find('input[type=checkbox]').each(function(i,o){
names[names.length] = $(o).attr('name');
});
var value = names.join();
var hidden = $('<input>').attr('type', 'hidden').attr('name', 'names').attr('value', value);
element.append(hidden);
});
});
</script>
</head>
<body>
<?php
$post_id = $_REQUEST['post_id'];
if(!empty($post_id)){
$names = $_REQUEST['names'];
$names = explode(',', $names);
foreach($names as $name){
$value = $_REQUEST[$name];
if($value != "on") $value = "off";
print "$name:$value<br/>";
}
}
?>
<form action="test.php" method="post">
<input type="hidden" name="post_id" value="<?php echo md5(date('Hms').session_id()); ?>" />
<table style="width:100%">
<tr>
<th>Name</th>
<th>Option1</th>
<th>Option2</th>
</tr>
<tr>
<th>lili</th>
<th><input type="checkbox" name="lili_1"></th>
<th><input type="checkbox" name="lili_2"></th>
</tr>
<tr>
<th>thor</th>
<th><input type="checkbox" name="thor_1"></th>
<th><input type="checkbox" name="thor_2"></th>
</tr>
<tr>
<th>fred</th>
<th><input type="checkbox" name="fred_1"></th>
<th><input type="checkbox" name="fred_2"></th>
</tr>
</table>
<button type="submit">Update</button>
</form>
</body>
</html>

process hidden field with jquery and calculate

I have an html table I've updated to use checkboxes to be able to delete multiple files:
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Date Created</th>
<th>Video Size</th>
<th>Video Length</th>
<th>
<button type="submit" class="deletebutton" name="delete_video" value="Delete" title="Delete the selected videos" onClick="return confirm('Are you sure you want to delete?')">Delete</button><br>
<input type="checkbox" name="radioselectall" title="Select All" />
</th>
</tr>
</thead>
<tbody>
<?php
for($i=0;$i<$num_videos;$i++)
{
//do stuff
//Note: I'm looping here to build the table from the server
?>
<tr >
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo $result_videos[$i]["camera_name"]; ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo setlocalTime($result_videos[$i]["video_datetime"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo ByteSize($result_videos[$i]["video_size"]); ?>
</td>
<td onclick="DoNav('<?php echo $url; ?>');">
<?php echo strTime($result_videos[$i]["video_length"]); ?>
</td>
<td>
<form name="myform" action="<?php echo htmlentities($_SERVER['REQUEST_URI']); ?>" method="POST">
<input type="checkbox" name="radioselect" title="Mark this video for deletion"/>
<input type="hidden" name="video_name" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
</form>
</td>
</tr>
I started with first creating some jquery code to create a select all/deselect all button in the table heading and just a test to show I can find which boxes are checked. That all works:
//selectall checkboxes - select all or deselect all if top checkbox is marked in table header
$("input[name='radioselectall']").change(function()
{
if( $(this).is(':checked') )
{
$("input[type='checkbox']","td").attr('checked',true);
}
else
{
$("input[type='checkbox']","td").attr('checked',false);
}
});
//process checkboxes - which ones are on
$(".deletebutton").click(function() {
$("input[name='radioselect']:checked").each(function(i){
alert(this.value);
});
});
So the part where I'm stuck is I don't know where to go from here. I need to pass all the video_names of all the videos selected (with the checkboxes). video_name is part of a hidden field in my form. So I need to pass that to my php function when the delete button is selected. Not really sure how to tackle this. Hope this makes sense.
Simple solution maybe:
Change your checkboxes to have a value of 1 and a name of $result_videos[$i]["video_name"]; in the table rows, make the form encapsulate the whole table.
Then on submit you can do something like:
foreach ($_POST as $key => $value) {
//Delete $key (the name) where $value == 1
}
Your approach is fine if you want to access the hidden fields through jQuery at a given point but once you submit the form and lose the DOM, the PHP processing page will have no way to relate the selected checkboxes with the hidden fields as there is no consistent naming scheme.
One approach would be to use the loop counter to suffix the two in order to pair them up:
<input type="checkbox" id="radioselect_<?= $i ?>" title="Mark this video for deletion" value="1" />
<input type="hidden" id="video_name_<?= $i ?>" value="<?php echo $result_videos[$i]["video_name"]; ?>" />
This would be good if you want to relate more than the two fields. Otherwise, you could just use the video_name as the value of the checkbox, as Ing suggested.

Categories