Read value from backed table once in bootstrap modal - javascript

I'm trying to read value from table once modal show with form.
I'm not able to get value from table behind modal. is there any specific rules?
What am I doing wrong? Would like to read value of backed table fields and wants to use for calculation of the modal fields.
please check example here -
Sample Code
/*doesn't read value of rollno from table when modal input box on change*/
$('#frm_name').change(function() {
var $row = $(this).closest('tr');
var rowID = $row.attr('class').split('_')[1];
var rollno = $row.find('.td_rollno').text();
alert(rollno);
});
HTML
<table class="table table-responsive">
<thead>
<tr>
<th>NAME</th>
<th>ROLL NUMBER</th>
<th>CONTACT NO</th>
<th>ADDRESS</th>
<th>EDIT</th>
</tr>
</thead>
<tbody>
<tr class="trID_1">
<td class="td_name">Name Row1</td>
<td class="td_rollno">12345</td>
<td class="td_contact">Mickey Mouse</td>
<td class="td_address">123 Mouse Lane</td>
<td>
<button class='td_btn btn btn-link btn-custom dis'>EDIT</button>
</td>
</tr>
<tr class="trID_2">
<td class="td_name">Name Row2</td>
<td class="td_rollno">22222</td>
<td class="td_contact">Wiley Coyote</td>
<td class="td_address">RR3 Road Runner Lane</td>
<td>
<button class='td_btn btn btn-link btn-custom dis'>EDIT</button>
</td>
</tr>
<tr class="trID_3">
<td class="td_name">Name Row3</td>
<td class="td_rollno">33333</td>
<td class="td_contact">Pepe LePew</td>
<td class="td_address">88 Stink Street</td>
<td>
<button class='td_btn btn btn-link btn-custom dis'>EDIT</button>
</td>
</tr>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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" id="myModalLabel">EDIT RECORD</h4>
</div>
<div class="modal-body">
<form id="updateValues" action="update.php" method="POST" class="form">
<div class="form-group">
<label for="name">NAME</label>
<input type="text" class="form-control" name="name" id="frm_name">
</div>
<div class="form-group">
<label for="contact">CONTACT</label>
<input type="text" class="form-control" name="contact" id="frm_contact">
</div>
<div class="form-group">
<label for="address">ADDRESS</label>
<textarea class="form-control" rows="3" name="address" id="frm_address"></textarea>
</div>
<input type="hidden" name="frm_id">
<input type="submit" class="btn btn-primary btn-custom" value="Save changes">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<div id="results"></div>
</div>
</div>

Your markup suggests trying to update a record with a modal form that posts to update.php. Separately, you have a jQuery function that looks like an attempt to update the table contents with the modal inputs.
If I understand you correctly, you will want to instead read the docs for your particular PHP framework for how to:
submit forms via AJAX
handle successful update with a script that will update the DOM accordingly

Related

get id from another table in javascript modal

Hello, good afternoon. I wanted to see how to get the id of the roles in this case, I can retrieve all the user data in my modal. But I can't get the role back since it belongs to another table and when I ask for it, it brings me the whole table. Since I use a many-to-many relationship
This is my js
$('.table .editBtn').on('click', function (event) {
event.preventDefault();
var href = $(this).attr('href');
$.get(href, function (usuario) {
$('.myForm #idUsuarioEdit').val(usuario.idUsuario);
$('.myForm #nombreEdit').val(usuario.nombre);
$('.myForm #apellidoEdit').val(usuario.apellido);
$('.myForm #emailEdit').val(usuario.email);
$('.myForm #rolesEdit').val(usuario.roles);
});
$('.myForm #editModal').modal();
});
This is my controller
#GetMapping("/editarUsuario")
#ResponseBody
public Usuario editarUsuario(Model model, long idUsuario) throws Exception {
model.addAttribute("listaUsuarios", usuarioService.getAllUsers());
model.addAttribute("roles", rolDao.findAll());
return usuarioService.getUsuarioById(idUsuario);
}
This is my html button
<table id="listaUsuarios" class="table table-bordered table-hover table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">E-mail</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="usuario : ${listaUsuarios}">
<td th:text="${usuario.idUsuario}"></td>
<td th:text="${usuario.nombre}"></td>
<td th:text="${usuario.apellido}"></td>
<td th:text="${usuario.email}"></td>
<td><div class="text-center">
<span th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')} or (${#authorization.expression('hasRole(''ROLE_USER'')')} and ${#httpServletRequest.remoteUser==usuario.email})">
<a class="btn btn-success editBtn" th:href="#{editarUsuario/(idUsuario=${usuario.idUsuario})}">Editar <i class="fas fa-edit"></i></a>
</span>
<span th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}"> |
<a class="btn btn-danger" href="#" th:onclick="'javascript:confirmaEliminar(\''+ ${usuario.idUsuario} +'\');'">Eliminar <i class="fas fa-user-times"></i></a>
</span>
</div>
</td>
</tr>
</tbody>
</table>
This is my modal
<div class="myForm">
<form th:object="${editarUsuario}" th:action="#{/editarUsuario}" method="post">
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Editar usuario</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<input class="form-control" type="hidden" id="idUsuarioEdit" name="idUsuario" />
</div>
<div class="form-group">
<label class="col-form-label" for="nombre">Nombre:</label>
<input class="form-control" type="text" id="nombreEdit" name="nombre" required />
</div>
<div class="form-group">
<label class="col-form-label" for="apellido">Apellido:</label>
<input class="form-control" type="text" id="apellidoEdit" name="apellido" required />
</div>
<div class="form-group">
<label class="col-form-label" for="email">E-mail:</label>
<input class="form-control" type="text" id="emailEdit" name="email" required />
</div>
<div class="form-group">
<label class="col-form-label" for="rol">Rol:</label>
<input class="form-control" type="text" id="rolesEdit" name="roles" required />
<!--<select class="form-control" id="rolesEdit" name="rol">
<option th:each="rol :${roles}" th:value="${rol.idRol}" th:text="${rol.nombre}"></option>
</select>-->
</div>
<!-- <div class="form-group">
<label class="col-form-label" for="rol">Rol:</label>
<select class="form-control" id="rolesEdit" name="roles">
<option th:each="rol :${roles}" th:value="${rol.idRol}" th:text="${rol.nombre}"></option>
</select>
</div>
ERROR MESSAGE
<div class="content">
<div style="text-align: center;" class="alert-danger-registro" th:if="${formErrorMessage}" th:text="${formErrorMessage}">Error Message</div>
-->
</div>
<!--FOOTER-->
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<input type="submit" class="btn btn-primary" value="Guardar cambios"/>
</div>
</div>
</div>
</div>
</form>
</div>
And.. my method for edit user
//metodo editar usuario
#Override
public Usuario editarUsuario(Usuario fromUser) throws Exception {
Usuario toUser = getUsuarioById(fromUser.getIdUsuario());
mapUser(fromUser, toUser);
return usuarioDao.save(toUser);
}
//Mapeamos todo menos el password.
protected void mapUser(Usuario from, Usuario to) {
to.setNombre(from.getNombre());
to.setApellido(from.getApellido());
to.setEmail(from.getEmail());
to.setRoles(from.getRoles());
}
currently this is what i receive:
modal edit
I've been trying for a long time but I can't receive the role id, thanks. Greetings
Try to explain where is the real problem, do you use some library or framework ?
You may try to find about how to join tables using the lib or the framework you are currently using.
Or you just have to return the roles you have fetched with the user data, something like :
const allRoles = //fetch roles
const userInfo = //fetch user info
return {userData: userInfo, roles: allRoles}

Fetching from table to edit record on Modal form

I'm trying to fetch data into fields from a table to edit record on database
I use code below, but in Chrome Console i have a js error: $tr is not definited
In fact seem this line have a problem: $tr = $(this).closest('tr');
When I open modal i cant get data in fields.
Any help to fix this?
TXS
TABLE
<table class="table table-bordered table-dark">
<thead>
<tr>
<th scope="col"> ID </th>
<th scope="col"> Message</th>
<th scope="col"> Button</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $opportunity_follow_up_id; ?></td>
<td><?php echo $opportunity_follow_up_message; ?></td>
<td><button type="button" class="btn btn-dark edit_followup">
Edit Follow-up</button>
</td>
</tr>
</tbody>
</table>
JS
$(document).ready(function(){
$(document).on('click', '.edit_followup', function(){
$('#edit_followup').modal('show');
alert ('working!');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#update_id').val(data[0]);
$('#opportunity_follow_up_message').val(data[1]);
});
});
MODAL
<div class="modal fade text-left modal-borderless" id="edit_followup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel33" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel33">New Follow-up </h4>
</div>
<form action="action/record_opportunities_follow_up.php" method="post" novalidate>
<input type="hidden" id ="opportunity_follow_up_opportunities_id" name="opportunity_follow_up_opportunities_id" value="<?php echo $opportunities_id; ?>" />
<div class="modal-body">
<div class="form-group">
<div class="controls">
<label>Follow-up Message</label>
<textarea data-length=250 class="form-control char-textarea" id="opportunity_follow_up_message" name="opportunity_follow_up_message" rows="3" placeholder="*" required data-validation-required-message="Required"></textarea>
<small class="counter-value float-right"><span class="char-count">0</span> / 250 </small>
</div>
</div>
<input type="hidden" name="update_id" id="update_id">
<div class="form-group">
<div class="controls">
<label>Next follow-up Date</label>
<input type="text" id ="opportunity_follow_up_message" name="opportunity_follow_up_message" value="" placeholder="dd-mm-aaaa" class="form-control">
</div>
</div>
<div class="form-group">
<div class="controls">
<label>Next follow-up Time</label>
<input type="text" id ="opportunity_follow_up_next_time" name="opportunity_follow_up_next_time" value="" placeholder="hh:mm:ss" class="form-control" data-mask="00:00:00">
</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input bg-primary" name="opportunity_follow_up_completed" id="opportunity_follow_up_completed" value="1">
<label class="custom-control-label" for="opportunity_follow_up_completed">Mark follow-up as complete</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" name="updatedata" value="save" class="btn btn-primary ml-1 block-page">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">UPDATE</span>
</button>
</div>
</form>
</div>
It seems like you have use strict in your file. And it doesn't allow you to declare variables without var, let or const
So declare your variable
Either by var, let or const
In your case you are not changing variable value so const is more preferable.
Like
const $tr = $(this).closest('tr');

How do I put data to my second select element via AJAX?

I need help! I have a button where whenever it's clicked, a modal pops out. This is my modal:
modal_newDelivery.php
<div class="modal fade" id="modal_new_delivery" tabindex="-1" role="dialog" aria-labelledby="newProductFormLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="newProductFormLabel">New Delivery</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="container">
<div class="form-group row">
<div class="col-6">
<label for="txt_drnumber">DR#</label>
<input class="form-control" type="text" id="txt_drnumber">
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label for="txt_supplier">Supplier</label>
<input class="form-control" type="text" id="txt_supplier">
</div>
</div>
<table class="table table-bordered" id="table_new_delivery">
<thead>
<tr>
<th>ITEM</th>
<th colspan="2">QTY(pcs)</th>
</tr>
</thead>
<tbody>
<tr>
<td><select class="form-control" id="select_products"></select></td>
<td><input type="text" class="form-control" id="txt_qty" onkeypress="return isNumberKey(event)"></td>
<td><button type="button" class="btn btn-danger remove" class="removerow">-</button></td>
</tr>
</tbody>
</table>
<br>
<button type="button" class="btn btn-info" style="width:100%;" onclick="newrow()">ADD A NEW ROW</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" onclick="clear()">Clear</button>
<button type="button" class="btn btn-primary" onclick="">Save</button>
</div>
</div>
</div>
</div>
As soon as that modal pops out, this AJAX code is called:
function loadselectproducts(){
$.ajax({
url: 'ajax.php',
method: 'POST',
data: {
key: 'inventory_delivery_loadproducts'
},success: function(response){
$('#select_products').html(response);
},error: function(xhr,ajaxOptions,thrownError){
console.log(xhr);
}
});
}
In my modal. There's a table. one of the td is a select.
WHAT HAPPENS IS THIS:
When you click the ADD A NEW ROW button, it will add a row with a select element on it. BUT the newly-added select element doesn't have any data unlike to the first select element.
THIS IS THE CODE WHEN THE ADD A NEW ROW BUTTON IS CLICKED:
var row = '<tr><td><select class="form-control" id="select_products"></select></td><td><input type="text" class="form-control" id="txt_qty" onkeypress="return isNumberKey(event)"></td><td><button type="button" class="btn btn-danger remove" class="removerow">-</button></td></tr>';
function newrow(){
$('#table_new_delivery tbody').append(row);
console.log(row);
loadselectproducts();
}
Yes, a new row is added, BUT the select element of the newly-added row doesn't have any data. I want to have the same data of my first select element to my newly-added select element.
Can you please help? I know this is a newbie problem.
Thank you,
Carl

To set radio button in the modal from a value using jquery

I am trying to set the radio button in the Modal by using the data attribute value. It works fine if I remove the hidden modal code. However, i want that code as I also use it to add new students(which I have not provided in code) and so i clear it on closing. The textbox works fine but the radio button stops working after selecting one student and then selecting another student.
For ex, I edit John and it works as expected. Now after clicking John and then i close and click Jane the radio button does not work. Is there a way where I can clear the content of the controls on closing the modal but also get the values back in on selection?
$(document).on('click', '.editStudent', function(e) {
var row = $(this).closest('tr');
var name = row.find('td.name').text().trim();
var qualified = $(this).attr("data-qualified");
if (name != null && name != "" && name != undefined) {
$("#ModalName").val(name);
}
if (qualified != null && qualified != "" && qualified != undefined) {
$("input[name='ModalQualified']").val([qualified.toLowerCase()])
}
$('#EditModal').modal('toggle');
})
$('#EditModal').on('hidden.bs.modal', function(e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", false)
.end();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet" />
<table id="tblStudent">
<thead>
<tr>
<th style="display:none;">Id</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display:none;"><input type="hidden" value="id1" /></td>
<td class="name">John</td>
<td><a title="Edit" class="btn btn-xs editStudent" data-qualified="false"> Edit</a></td>
</tr>
<tr>
<td style="display:none;"><input type="hidden" value="id2" /></td>
<td class="name">Jane</td>
<td><a title="Edit" class="btn btn-xs editStudent" data-qualified="true"> Edit</a></td>
</tr>
<tr>
<td style="display:none;"><input type="hidden" value="id3" /></td>
<td class="name">Jim</td>
<td><a title="Edit" class="btn btn-xs editStudent" data-qualified="false"> Edit</a></td>
</tr>
</tbody>
</table>
<div id="EditModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Edit Student</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<label>Student</label><br />
<input type="text" id="ModalName" class="form-control medium" />
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="form-group">
<label for="Refrigeration">Qualified</label>
<input type="radio" id="ModalQualified" name="ModalQualified" value="true" />Yes
<input type="radio" id="ModalQualified" name="ModalQualified" value="false" style="margin-left: 15px;" />No<br />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The ID of the radio would have to be different, and then use prop of element:
if(qualified.toLowerCase() == 'true')
$('#ModalQualifiedY').prop('checked',true)
else
$('#ModalQualifiedN').prop('checked',true)

Form is presenting same data in php while loop

I am trying to get an edit form to work with the loop in the php. I have a delete button and it works just fine. The edit form keeps presenting only the first row in the table. In firebug, it shows that all the other forms are there with the correct unique id for each but only the first form shows when edit is clicked on different rows. Can someone help me as to why?
<table id="table_id" class="table table-hover table-striped">
<thead>
<tr>
<th>ID #</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($search_sql)) {
?>
<tr>
<td id = "clicked"><?=$row['ID']?></td>
<td id = "clicked"><?=$row['Product']?></td>
<td id = "clicked"><?=$row['Quantity']?></td>
<td id = "clicked">$ <?=$row['Price']?></td>
<td>
<button class="btn btn-warning btn-sm" onclick="div_show2(this, '<?=$row['ID']?>'); return false;"><span class="glyphicon glyphicon-edit"></span>Edit</button>
<!-- Modal for the Edit Data Form -->
<div id ="hidden-form2">
<div id = "popupContact">
<form action= "updateData.php" id = "editForm<?=$row['ID']?>" method="POST" name="editForm">
<input type="hidden" name="ID" value="<?=$row['ID']?>">
<div class="form-group">
<label for="product">Product</label>
<input type="text" class="form-control" id="product<?=$row['ID']?>" name="product" value="<?=$row['Product']?>">
</div>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="text" class="form-control" id="quantity<?=$row['ID']?>" name="quantity" value="<?=$row['Quantity']?>">
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price<?=$row['ID']?>" name="price" value="<?=$row['Price']?>">
</div>
<button type="button" class="btn btn-default" onclick="formHide2()">Close</button>
<button type="submit" id="save" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
<!--End of Edit Form-->
</td>
<td>
<!--Delete Button Form-->
<form method="post" action="deleteData.php">
<button class="btn btn-danger btn-sm" type="submit"><span class="glyphicon glyphicon-trash"></span>Delete</button>
<input type="hidden" id="ID" name="ID" value="<?=$row['ID']?>">
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
//script for calling the edit forms as a modal popup
//Function To Display Popup for Edit form
function div_show2() {
document.getElementById("editForm").reset();
document.getElementById('hidden-form2').style.display = "block";
}
//Function to Hide Popup
function formHide2(){
document.getElementById('hidden-form2').style.display = "none";
}
Your show_div2 function is only showing one element.
document.getElementById('hidden-form2').style.display = "block";
That shows you why you are only seeing the first row.
Update your HTML and Javascript as follows
HTML
<div id="hidden-form2<?=$row['ID']?>">
Javascript
function div_show2(id) {
document.getElementById("editForm"+id).reset();
document.getElementById('hidden-form2'+id).style.display = "block";
}
To avoid having any problems like this in the future, always make sure that your id's are unique.
The first 4 td I see all use the same id name clicked. Try to fix that first and see what happens.
<td class="clicked" id="clickedID<?=$row['ID']?>"><?=$row['ID']?></td>
<td class="clicked" id="clickedProduct<?=$row['ID']?>"><?=$row['Product']?></td>
<td class="clicked" id="clickedQuantity<?=$row['ID']?>"><?=$row['Quantity']?></td>
<td class="clicked" id="clickedPrice<?=$row['ID']?>">$ <?=$row['Price']?></td>

Categories