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

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

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}

Using JavaScript: Using a modal class when i am editing a specific html table row. how to select the current value on a dropdownlist?

I am new in this!
I have a table of content with the tag [Name, Gender and Age]. When editing a line, using the modal class, the dropdownlist doesn't take the select table value as the default value on the dropdownlist, it will show it empty.
Tx!
AC
<div class="modal fade" id="modal-edit">
<div class="modal-dialog">
<div class="modal-content">
<form action="page.php" method="POST" class="form-horizontal">
<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">Edit</h4>
</div>
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="item0" id="item0" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<select class="form-control select2" name="item1" id="item1" >
<option></option>
<option>Female</option>
<option>Male</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Age</label>
<div class="col-sm-10">
<input name="item2" id="item2" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<button type="Submit" name="update" class="btn btn-primary">Edit</button>
</div>
</form>
</div>
</div>
</div>
Check my snippet and its working fine as your need & instructions with using of select2 plugin for drop-down Gender selection.
I hope below snippet will help you lot.
$(document).ready(function(){
$('.select2').select2({
minimumResultsForSearch: -1 //Search field hide
});
});
$('#modal-edit').on('show.bs.modal', function(e) {
// e.relatedTarget -> to find which button clicked
var getName = $(e.relatedTarget).parents()[1].cells[0].innerText;
var getGender = $(e.relatedTarget).parents()[1].cells[1].innerText;
var getAge = $(e.relatedTarget).parents()[1].cells[2].innerText;
$('#item0').val(getName);
$('#item1').val(getGender);
$('#item2').val(getAge);
$(".select2").select2({minimumResultsForSearch: -1}); //after value set in drop-down list then again reinitialize
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<br>
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
<th width="120">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ricky</td>
<td>Male</td>
<td>40</td>
<td><button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#modal-edit"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
<tr>
<td>Mikolo</td>
<td>Female</td>
<td>38</td>
<td><button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#modal-edit"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
<tr>
<td>Simora</td>
<td>Female</td>
<td>28</td>
<td><button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#modal-edit"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
<tr>
<td>Raeesh</td>
<td>Male</td>
<td>29</td>
<td><button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#modal-edit"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
<tr>
<td>Yuvraj</td>
<td>Male</td>
<td>37</td>
<td><button type="button" class="btn btn-sm btn-info" data-toggle="modal" data-target="#modal-edit"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="modal fade" id="modal-edit">
<div class="modal-dialog">
<div class="modal-content">
<form action="'.$page.'" method="POST" class="form-horizontal">
<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">Edit</h4>
</div>
<div class="modal-body">
<div class="box-body">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="item0" id="item0" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<select class="form-control select2" name="item1" id="item1" data-width="100%">
<option value="Female">Female</option>
<option value="Male">Male</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Age</label>
<div class="col-sm-10">
<input name="item2" id="item2" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="Submit" name="update" class="btn btn-primary">Save & Update</button>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
I think you want show default value in drop down like this.
add value for each option in select box and make one option selected by add selected attribute.
<select class="form-control select2" name="item1" id="item1" >
<option selected>Please Select Gender</option>
<option value="female">Female</option>
<option value="male">Male</option>
</select>
edited
<script>
var gender='male'; // you variable may have value 'male' or 'female'
$('#item1').val(gender);

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)

Read value from backed table once in bootstrap modal

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

Validate bootstrap modal fields on click of button

I am using twitter bootstrap modal to get 'Start' and 'End' date for some course.
<div id="save_course_modal" class="modal hide fade">
<div class="modal_header_class">
<h4>Start Course</h4>
</div>
<div class="modal-body">
<label class='selector_modal_label'>Course</label>
<table class="table">
<thead>
<tr>
<th>
<p>Start date: <input type="text" id="start_date" size="30" /></p>
</th>
<th>
<p>End date: <input type="text" id="end_date" size="30" /></p>
</th>
</tr>
</thead>
</table>
</div>
<div class="modal-footer modal_footer_class">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id='add_course' class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Start</button>
</div>
</div>
My Use Case:
I want to validate two input fields with ids 'start_date' and 'end_date'.
Since, it is not a form and hence couldn't use 'required' attribute.
I am thinking to use following:
Remove data-dismiss="modal" aria-hidden="true" from
button with id='add_course'.
Add onclick='validate_course_fields();' to above button.
If validations are fine then hide modal through $('#save_course_modal').hide();
Any better solution is appreciated.
First it would be best to avoid using tables to align the elements in modal.
<div id="save_course_modal" class="modal hide fade">
<div class="modal_header_class">
<h4>Start Course</h4>
</div>
<div class="modal-body">
<label class='selector_modal_label'>Course</label>
<div class="form-group">
<label class="control-label col-sm-2"> Start Date:</label>
<div class="col-sm-10>
<input type="text" id="start_date" class="form-control" size="30" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"> End Date:</label>
<div class="col-sm-10>
<input type="text" id="end_date" class="form-control" size="30" />
</div>
</div>
</div>
<div class="modal-footer modal_footer_class">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button id='add_course' class="btn btn-primary">Start</button>
</div>
</div>
In your javascript code you should use the event hide of the Bootstrap that can be seen in http://getbootstrap.com/javascript/#modals
$("#add_course").click(function(e){
e.preventDefault(); //remove the default button action
//validation
if(validate_form()){
//When validation is OK
//hide modal using event of the Bootstrap
$("#save_course_modal").modal("hide");
}
})

Categories