how to update with modal bootstrap and checkbox - php

hey guys how can i update multiple rows with checkbox and display modal bootstrap after pressing update button?
example like this:
I checked the line with the checkbox
After that I press "Pindah Department" or in english "Move Departemen"
actually I do not need the edit book () function, I only need one function and the funtion it can call modal bootstrap pops up, to update from the dropdown menu"
i forgot to change save button to call function prepareData(), pop up appears, but I do not know what it is
I can only edit it one by one, with Modal Bootstrap, how can i be like above that?
this is my view:
<table id="emp_id" class="table table-bordered dt-responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</thead>
<tbody>
<?php
foreach($data as $d){
?>
<tr>
<td>
<input class="childbox" width="1%" type="checkbox" name="msg[]" id="id" align="center" value="<?php echo $d['emp_id'] ?>" />
</td>
<td width="1%" align="center"><?php echo $d['emp_id']; ?></td>
<td><button class="btn btn-light" onclick="edit_book(<?php echo $d['emp_id'];?>)"><i class="glyphicon glyphicon-pencil"></i></button></td>
<td class="data-check"><?php echo $d['first_name']; ?></td>
<td class="data-check"><?php echo $d['nik']; ?></td>
<td class="data-check"><?php echo $d['gender']=='0' ? 'Laki-Laki' : 'Perempuan'; ?></td>
<td class="data-check"><?php echo $d['pin']; ?></td>
<td class="data-check"><?php echo $d['dept_name']; ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</tfoot>
</table>
this is my script to bring up modal bootstrap and for checkbox functions:
<script type="text/javascript">
$(document).ready( function () {
$('#emp_id').DataTable( {
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
} );
$("input[name='checkAll']").click(function() {
var checked = $(this).attr("checked");
$("#emp_id tr td input:checkbox").attr("checked", checked); });
} );
function toggle(id) {
checkboxes = document.getElementsByName('msg[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = id.checked;
}
}
function add_book()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_book(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('proses/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="emp_id"]').val(data.emp_id);
$('[name="dept_id_auto"]').val(data.dept_id_auto);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Departemen'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
</script>
and this is my modal bootstrap :
<div id="modal_form" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Tambah Siswa</h4>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label for="colFormLabelLg" class="col-sm-4 col-form-label col-form-label-lg">Pilih Departemen Baru</label>
<div class="col-sm-6">
<select name="dept_id_auto" class="form-control pull-right">
<?php
foreach($groups as $row)
{
echo '<option name="dept_id_auto" value="'.$row['dept_id_auto'].'">'.$row['dept_name'].'</option>';
}
?>
</select>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
and this is my controller :
public function book_update()
{
$data = array(
'dept_id_auto' => $this->input->post('dept_id_auto'),
);
$this->Pindah_dept_model->book_update(array('devid_auto' => $this->input->post('devid_auto')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->Pindah_dept_model->get_by_id($id);
echo json_encode($data);
}
and this is my model :
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('emp_id',$id);
$query = $this->db->get();
return $query->row();
}
public function book_update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
hey Eiji can you modify this code because, if I use this code I can do multiple update rows, but this code does not display modal bootstrap, it's just this code directly call the function in the controller, but have the same concept only this code can not display modal bootstrap, please
function update(id)
{
var list_id = [];
$("#id:checked").each(function() {
list_id.push(parseInt(this.value));
});
console.info(JSON.stringify(list_id));
if(list_id.length > 0)
{
if(confirm('Are you sure update this '+list_id.length+' data?'))
{
$.ajax({
type: 'POST',
data: {'devid_auto': list_id},
url: '<?php echo site_url('setting/mesin_update')?>',
success: function(result)
{
var hasil = result.replace(/\s/g,'');
if(hasil == 'y')
{
alert("Data Berhasil di Update");
location.reload();
}
else
{
alert('Failed.');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error update data');
}
});
}
}
else
{
alert('no data selected');
}
}

Small correction in your html, Please delete the id="id", this is a big mistakes, because the id shoud be unique.
<input class="childbox" width="1%" type="checkbox" name="msg[]" align="center" value="" data-userid="<?php echo $d['emp_id'] ?>"/>
you have to define which of your line has been checked.
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
you find what is the option selected.
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
You have to pass all this to your ajax request. So there is your ajax and a new function to add
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: prepareData(), //<-- here we call it
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function prepareData(){
$data = [];
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
//select the new debt value
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
return data;
}
Now, in your controller, you should have two post data :
* new_dept, which content an int of the new dept
* user_id_list, which is an array of id.
So you just need to adapt your model and it's over.
Change the line
<div class="modal-footer">
<!-- change here -->
<button type="button" id="btnSave" onclick="prepareData()" class="btn btn-primary">Save</button>
<!-- end change -->
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
Then, in your javascript function prepareData()
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
//add this line for the debugging
alert( JSON.stringify(data) )
//this will display the current data value, even if it's an array/object or whatever
return data;

you can use my code for referenction
<td>
<button class="btn btn-success" data-toggle="modal" data-target="#r<?php echo $rule2->id_forward;?>">Edit </button>
<?=anchor('guru/hapus_rule/'.$rule2->id_forward,'Hapus',['class'=>'btn btn-danger btn-sm'])?>
</td>
<div class="modal modal-success" id="r<?php echo $rule2->id_forward;?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title" align="center">Edit Rule</h4>
</div>
<div class="modal-body">
<?php echo form_open_multipart('guru/ubah_rule/'.$rule2->id_forward);?>
<div class="form-group">
<label for="Kondisi">Kondisi 1</label>
<select class="form-control" name="kondisi">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_1==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_2">Kondisi 2</label>
<select class="form-control" name="kondisi_2">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_2==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_3">Kondisi 3</label>
<select class="form-control" name="kondisi_3">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_3==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_4">Kondisi 4</label>
<select class="form-control" name="kondisi_4">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_4==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_5">Kondisi 5</label>
<select class="form-control" name="kondisi_5">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_5==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="hasil">Hasil</label>
<input type="text" name="hasil" class="form-control" value="<?php echo $rule2->hasil; ?>">
</div>
<div class="form-group">
<label for="artikel">Artikel</label>
<select class="form-control" name="id_artikel">
<option value="">Pilih</option>
<?php foreach ($artikel as $data_rule) { ?>
<option value="<?php echo $data_rule->id_artikel; ?>" <?php if($rule2->id_artikel==$data_rule->id_artikel){echo "selected";} ?> ><?php echo $data_rule->judul; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputFile">File Pembelajaran</label>
<input type="file" name="berkas" id="exampleInputFile">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline">Save changes</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
</div>

Related

Pass data from bs modal to cloned input fields

So i have this issue trying to pass data from bs modal to form inputs, the logic is when i type in first row and press enter a bs modal pops up and show data from database in a table every row has its respective select button so when i click select the chosen row fills up the input fields in the form but after cloning the next rows of inputs and repeat the steps to fill the form from bs modal this only updates all of the fields with same data
Here is an image of the issue
here's my code i've been stuck here for days..
<script>
$(document).ready(function() {
$(".card").on('keyup', '.live_search', function() {
var input = $(this).val();
if (input != "") {
$.ajax({
type: "POST",
url: "livesearch.php",
data: {
input: input
},
success: function(data) {
$(".searchresult").html(data);
$(".searchresult").css("display", "block");
}
});
} else {
$(".searchresult").css("display", "none");
}
});
$(".add-row").click(function(e) {
e.preventDefault();
$("#show-item").prepend(`<tr>
<input type="hidden" name="id[]">
<td class="col-2">
<div class="input-group input-group-sm">
<a href="#" class="btn btn-danger delete-row"> <i class="fa-solid fa-trash-can"></i>
</a>
<input type="text" class="form-control live_search" name="material_name[]" placeholder="Nombre Material">
</div>
</td>
<td class="col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_one[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="measure_two[]">
</div>
</td>
<td class=" col-2">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="unit_measure[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="length[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm ">
<input type="text" class="form-control" name="width[]">
</div>
</td>
<td class=" col-1">
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="price[]">
</div>
</td>
</tr>`);
});
// remove product row
$('.card').on('click', '.delete-row', function(evt) {
evt.preventDefault();
$(this).closest('tr').remove();
});
// modal pops up when pressing enter
$('.card').on('keyup', '.live_search', function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
// $('.modal').modal('show');
var product = $(this);
$('#insert').modal('show', {
backdrop: 'static',
keyboard: false
}).on('click', '#selected', function(e) {
var id = $(this).attr('data-material-id');
var material = $(this).attr('data-material-name');
var measure_one = $(this).attr('data-material-measure_one');
var measure_two = $(this).attr('data-material-measure_two');
var unit_measure = $(this).attr('data-material-unit_measure');
var length = $(this).attr('data-material-length');
var width = $(this).attr('data-material-width');
var price = $(this).attr('data-material-price');
$(product).closest('tr').find('[name="supplier_id[]"]').val(id);
$(product).closest('tr').find('[name="material_name[]"]').val(material);
$(product).closest('tr').find('[name="measure_one[]"]').val(measure_one);
$(product).closest('tr').find('[name="measure_two[]"]').val(measure_two);
$(product).closest('tr').find('[name="unit_measure[]"]').val(unit_measure);
$(product).closest('tr').find('[name="length[]"]').val(length);
$(product).closest('tr').find('[name="width[]"]').val(width);
$(product).closest('tr').find('[name="price[]"]').val(price);
$('#insert').modal('hide');
});
return false;
}
});
});
</script>
if (mysqli_num_rows($result) > 0) { ?>
<table class="table table-bordered table-striped table-hover table-sm text-center">
<thead class="table-primary">
<tr>
<th>ID</th>
<th>Proveedor</th>
<th>Material</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_assoc($result)) :
$id = $row['supplier_id'];
$supplier = $row['supplier'];
$material = $row['material'];
?>
<tr>
<td><?php echo $id ?></td>
<td><?php echo $supplier ?></td>
<td><?php echo $material ?></td>
<td>
<?php echo '<a href="#" class="btn btn-link" id="selected" datamaterial-id="' . $row['supplier_id'] . '"
data-material-name="' . $row['material'] . '" data-material-measure_one="' . $row['measure_one'] . '"
data-material-measure_two="' . $row['measure_two'] . '" data-material-unit_measure="' . $row['unit_measure'] . '"
data-material-length="' . $row['length'] . '" data-material-width="' . $row['width'] . '"
data-material-price="' . $row['price'] . '">Select</a>';
?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
This row in the last keyup eventlistener
var product = $(this);
will select every row.
Try this instead:
var product = $(e.target);
Read more about event.target here.

How to send a jQuery ID to Bootstrap Modal to use it in PHP function?

I know there are lots of similar posts but nothing really helps me. I'm trying to run a PHP function in Bootstrap Modal with two parameters, one of the parameter is a row ID that needs to go from jQuery.
I can send it and display it in a div id but how can I convert this parameter for a PHP function?
jQuery
$(document).ready(function() {
$("a").click(function(){
var hrefs = $(this).attr("href");
$("#modal_form").attr('action',hrefs);
var ids = hrefs.split("=").pop();
$("#sid").html(ids);
});
});
Bootstrap Modal
<!-- Update Record Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="updateModalLabel">Update Translation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="translation.php" id="modal_form" method="post">
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<?php selectedTranslation($dbh, $ids); ?> /*I need to run this function*/
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" name="update" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
php function
function getAllTranslationById($dbh, $id){
...
<?php
$sqlSelect = "SELECT * FROM xxxx";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
<td><img alt="Link" src="images/edit.png" title="Update this row"></td>
</tr>
<?php }?>
</table>
<?php }
php function
function selectedTranslation($dbh, $sid){
....
<?php
$sqlSelect = "SELECT * FROM xxxx ";
$result = mysqli_query($dbh, $sqlSelect);
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_text'] ?>" readonly="readonly"></td>
<td><input type="text" class="form-control" value="<?php echo $row['swrd_context'] ?>" ></td>
</tr>
<?php }?>
</table>
<?php }?>
Its just impossible like the way you want
So what you can do instead?
Use Ajax.
<div class="modal-body">
<div id="sid"></div> /* I'm getting the right ID here*/
<div id="ajaxResult"></div>
</div>
// JS Codes
$(document).ready(function() {
$("a").click(function(){
var sid = ""; // set your `sid` here
$.ajax({
url: "/url_here", //url to your PHP page
type: "post",
data: {id: sid},
success: function(data) {
$("#ajaxResult").html(data); //result html
}
});
});
});

How can I display dynamically in my select option my students with first name and last name

I'm beginner in Laravel. I'm using ajax. I want to display data of students (eleves) in my select option by first name (prénom) last name (nom), but the problem that it displays only the first name (prénom) without the last name (nom). However I need to associate first name and last name. Please help me.
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;
use App\Eleve;
use App\Classe;
use DB;
class DropdownlistController extends Controller
{
public function index()
{
$notes = Note::all();
$matieres = Matiere::all();
$eleves = Eleve::all();
$classes = Classe::all();
$classes = DB::table("classes")->pluck("classe","id");
return view('admin.dropdownlists',compact('classes','notes','matieres','eleves'));
}
public function store(Request $request)
{
Note::create($request->all());
return redirect()->back();
}
public function getStateList(Request $request)
{
$eleves = DB::table("eleves")
->where("classe_id",$request->classe_id)
->pluck("nom" ,"prenom","id");
return response()->json($eleves);
}
public function getCityList(Request $request)
{
$matieres = DB::table("matieres")
->where("classe_id",$request->classe_id)
->pluck("nom_matiere","id");
return response()->json($matieres);
}
}
My view there I'm using my function ajax
#extends('layouts.admin')
#section('content')
<section class="wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2> ESpace de Gestion <b></b> des notes </h2>
</div>
<div class="col-sm-6">
<a href="#addEmployeeModal" class=" btn btn-success" data-toggle="modal"><i class="material-icons"></i>
<span>Ajouter un nouvelle note </span></a>
</div>
</div>
</div>
<div class="row mt">
#if(session()->has('success'))
<div class="alert alert-success">
{{session()->get('success')}}
</div>
#endif
<div class="col-lg-12">
<div class="content-panel">
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-note</th>
<th>Nom</th>
<th>classe</th>
<th>matiére</th>
<th>Note</th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note)
<tr>
<td class="numeric" data-title="id-parent">{{$note->id}}</td>
<td class="numeric"
data-title="id-parent">{{$note->eleve->nom}} {{$note->eleve->prenom}}</td>
<td class="numeric" data-title="id-parent">{{$note->classe->classe}}</td>
<td class="numeric" data-title="id-parent">{{$note->matiere->nom_matiere}}</td>
<td class="numeric" data-title="Login">{{$note->note}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme"
data-target="#editEmployeeModal " data-catid={{$note->id}} class="edit"
data-toggle="modal"><i class="material-icons" data-toggle="tooltip"
title="Edit"></i></button>
<button href="#deleteEmployeeModal" class="btn btn-theme"
data-target="#deleteEmployeeModal" data-catid="{{$note->id}}"
class="delete" data-toggle="modal"><i class="material-icons"
data-toggle="tooltip"
title="Delete"></i>
</button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('dropdownlists.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter un éléve</h4>
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×
</button>
</div>
<div class="modal-body">
<div class="panel-body">
<div class="form-group">
<label for="title">Select classe:</label>
<select id="classe" name="classe" class="form-control"
style="width:350px">
<option value="" selected disabled>Select</option>
#foreach($classes as $key => $classe)
<option value="{{$key}}"> {{$classe}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select classe:</label>
<select id="eleve" name="eleve" class="form-control"
style="width:350px">
</select>
</div>
<div class="form-group">
<label for="title">Select matiere:</label>
<select id="matiere" name="matiere" class="form-control"
style="width:350px">
<option value="" selected disabled>Select</option>
</select>
</div>
<div class="form-group">
<label>la note </label>
<input type="text" id="note" name="note" class="form-control"
required>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal"
value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('js')
<script type="text/javascript">
$('#classe').change(function () {
var classeID = $(this).val();
if (classeID) {
$.ajax({
type: "GET",
url: "{{url('get-state-list')}}?classe_id=" + classeID,
success: function (res) {
if (res) {
$("#eleve").empty();
$("#eleve").append('<option>Select</option>');
$.each(res, function (key, value) {
$("#eleve").append('<option
value = "'+eleve.age+'" > '+value+' < /option>');
});
} else {
$("#eleve").empty();
}
}
});
} else {
$("#classe").empty();
$("#matiere").empty();
}
});
$('#classe').on('change', function () {
var classeID = $(this).val();
if (classeID) {
$.ajax({
type: "GET",
url: "{{url('get-city-list')}}?classe_id=" + classeID,
success: function (res) {
if (res) {
$("#matiere").empty();
$.each(res, function (key, value) {
$("#matiere").append('<option
value = "'+key+'" > '+value+' < /option>');
});
} else {
$("#matiere").empty();
}
}
});
} else {
$("#matiere").empty();
}
});
</script>
#endsection
Routes:
Route::resource('dropdownlists','DropdownlistController');
Route::get('get-state-list','DropdownController#getStateList');
Route::get('get-city-list','DropdownController#getCityList');
Laravel has a very powerful and very useful feature that will make this easy for you, mutators. By adding a 'fullName' mutator, you can do this in the model any time you want. Then, in your controllers, you can call the function as if it was a field.
So, on your Eleve model:
public function getFullNameAttribute(){
return $this->prenom. " " . $this->nom;
}
Then in any controller, like when you want to send these to a dropdown, you can just get your collection, and then transfer it into the array you need.
Get the collection:
$elevesCollection = \App\Eleve::orderBy('nom')->select('prenom', 'nom', 'id')->get();
Then, pull the full name and the id from the collection:
$eleves = $elevesCollection ->pluck('name', 'id')->toArray();
You can send that through to your form dropdown. Please double check my code / spelling, but this should do what you wish.

How to use outsider function of jquery document.ready

Here i am giving you snippet of my jquery source code. And this is wrote in separate JS file. Guide me how to access add_user function in directly.
if i wrote SRC = assets/js/functions.js. It will give me error of JS because i am using function directly on button onclick event. and I am using single form for ADD USER and EDIT USER.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<link href="<?php echo base_url() ?>assests/css/bootstrap.min.css"
rel="stylesheet">
<link href="<?php echo base_url() ?>assests/css/dataTables.bootstrap.css"
rel="stylesheet">
<link href="<?php echo base_url() ?>assests/css/custom.css"
rel="stylesheet">
</head>
<body>
<div class="col-md-10 col-md-offset-1">
<button class="btn btn-primary" id="btn_adduser" onclick="add_user()">Add
user</button>
<table id="table_id" class="table table-bordered" cellspacing="0" >
<thead>
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Status</th>
<th>Created</th>
<th>Modified</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($user as $user){?>
<tr>
<td><?php echo $user->id;?></td>
<td><?php echo $user->firstname;?></td>
<td><?php echo $user->lastname;?></td>
<td><?php echo $user->email;?></td>
<td><?php echo $user->status;?></td>
<td><?php echo $user->created_date;?></td>
<td><?php echo $user->modified_date;?></td>
<td>
<button class="btn btn-primary"
onclick="edit_user(<?php echo $user->id;?>)"><i class="glyphicon glyphicon-
pencil"></i></button>
<button class="btn btn-primary"
onclick="delete_user(<?php echo $user->id;?>)"><i class="glyphicon
glyphicon-
trash"></i></button>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<!--Add / Edit User Section-->
<div class="panel panel-primary col-md-6 col-md-offset-3" style="display:
none;">
<div class="panel-heading">Add user</div>
<div class="panel-body">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<input name="txt_fname" id="txt_fname"
placeholder="Firstname" class="form-control" type="text" required>
</div>
<div class="form-group">
<input name="txt_lname" id="txt_lname"
placeholder="Lastname" class="form-control" type="text" required>
</div>
<div class="form-group">
<input name="txt_email" id="txt_email" placeholder="Email
address" class="form-control" type="email" required>
</div>
<label class="control-label" for="radio_status">Status</label>
<div class="radio">
<label><input type="radio" name="radio_status" id="sta_active"
value="0">Active</label>
</div>
<div class="radio">
<label><input type="radio" name="radio_status"
id="sta_inactive" value="1">Inactive</label>
</div>
</div>
<div class="form-group col-md-6">
<button type="button" class="btn btn-primary" id="btnSave"
onclick="save()" >Save</button>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="button" class="btn btn-primary"
id="btn_hide">Hide</button>
</div>
</form>
</div>
</div>
<!-- End Add / Edit User Section-->
<script src="<?php echo base_url()?>assests/js/jquery-3.1.0.min.js">
</script>
<script src="<?php echo base_url()?>assests/js/bootstrap.min.js"></script>
<script src="<?php echo base_url()?>assests/js/jquery.dataTables.min.js">
</script>
<script src="<?php echo base_url()?>assests/js/dataTables.bootstrap.js">
</script>
<script src="<?php echo base_url()?>assests/js/functions.js"></script>
</body>
</html>
$(document).ready( function () {
$('#table_id').DataTable();
$("#btn_hide").click(function(){
$(".panel").slideUp(500);
});
});
var save_method; //for save method string
var table;
function add_user() {
save_method = 'add';
$(".panel").slideDown(500);
$(".panel-heading").text("Add user");
$('#form')[0].reset(); // reset form on modals
}
function edit_user(id) {
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('index.php/user/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="id"]').val(data.id);
$('[name="txt_fname"]').val(data.firstname);
$('[name="txt_lname"]').val(data.lastname);
$('[name="txt_email"]').val(data.email);
$(".panel").slideDown(500);
$(".panel-heading").text("Edit user");
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
function save() {
var url;
if(save_method == 'add') {
url = "<?php echo site_url('index.php/user/user_add')?>";
} else {
url = "<?php echo site_url('index.php/user/user_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
//if success close modal and reload ajax table
$(".panel").slideUp(500);
location.reload();// for reload a page
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Please enter valid data');
}
});
}
function delete_user(id) {
if(confirm('Are you sure delete this data?')) {
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('index.php/user/user_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data) {
location.reload();
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Error deleting data');
}
});
}
}
How to use function add_user directly on button's onClick event in HTML from external JS file.
function.js must be before jquery code
<script src='function.js'>
<script>
$(document).ready( function () {
$('#table_id').DataTable();
$("#btn_hide").click(function(){
$(".panel").slideUp(500);
});
$('button.class').click(function(){
add_user();
})
});
</script>

dropdown value is not getting selected ajax html() response

I have written a dependable dropdown and its first get the id from the first dropdown and set the div id of the second drop down through ajax call. The issue is when I try to do with html() the second drop down first value can not be selected.
Here is the image of the dependable dropdown
Here is the code I am trying:
<div class="modal fade" id="addNewFloor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" >
<div class="modal-dialog" role="document" style="">
<div class="modal-content">
<?php echo form_open('registrations/saveNewFloor'); ?>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<div class="modal-header">
<img src="assets/backend/img/floor.png" style="widows:50px;height:50px">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="myModalLabel">Register New Floor</h4>
</div>
<hr class="colorgraph">
<div id="floorModelBox"></div>
<div class="modal-body" style="margin-bottom:2px;padding-top:1px">
<table class="table table-condensed" style="background-color:#F5F5F5;margin-bottom:1px">
<caption><h3><small>Floor Path</small><h3></caption>
<!------- Select Branch --------------------->
<tr><td>Select Branch</td><td >
<select class="form-control" name="branchId_floorModel1" id="branchId_floorModel" onChange="return selectBuildings_floorModel(this.value);selectBuildings_floorModel323();clearFloors();clearSections();clearIots();clearGateways();myFunction();" >
<option value="0" selected> -- select Branch --</option>
<?php
foreach($groups as $row)
{
echo '<option value="'.$row->branchId.'">'.$row->branchName.'</option>';
}
?>
</select></td></tr>
<tr><td>Select Building</td><td>
<select class="form-control" name="buildingBox_floorModel1" style="width:100%;" id="buildingBox_floorModel" required>
<option selected ="selected" value="0">select Building</option></select>
</td></tr>
</table>
<hr/>
<table class="table table-condensed" style="margin-top:2px;margin-bottom:1px">
<caption><h3><small>Floor Details </small><h3></caption>
<tr><td>Floor Name :</td><td > <input type="text" class="form-control input-sm" name="floorName_FloorModel" id="floorName_FloorModel" /></td></tr>
<tr><td>Floor No : </td><td><input type="text" class="form-control input-sm" placeholder="building no" name="floorNo_FloorModel" id="floorNo_FloorModel" /></td></tr>
</table>
</div>
<div class="modal-footer" style="margin-bottom:2px;padding-top:1px">
<hr class="colorgraph">
<button type="button" class="btn btn-primary " data-dismiss="modal" onClick="window.location.reload();">CLOSE</button>
<?php echo form_submit(array( 'class'=>'btn btn-success ', 'id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
</div>
</div>
</div>
function selectBuildings_floorModel(branchId) {
$.ajax({
url: '<?php echo base_url();?>registrations/get_building_section/' + branchId ,
success: function (response)
{
jQuery('#buildingBox_floorModel').html(response);
}
});
}
//controller method
function get_building_section($branchId)
{
$this->MBuilding->get_building_by_branch($branchId);
$sections = $this->db->get_where('building' , array(
'branchId' => $branchId
))->result_array();
// print_r($sections);die;
foreach ($sections as $row) {
//echo $row['buildingName'];
//
echo '<option value="' . $row['buildingId'] . '">' . $row['buildingName'] . '</option>';
}
}
I even tried with the append() method, but then it's not clearing the dropdown list value.
Try Following...
$("#branchId_floorModel").change(function (){
// Your Code....
});

Categories