I've a few modals build on top of Twitter Bootstrap Modal, each have at least one submit button which is the default action I need to trigger in most cases since the second button is for go back (dismiss the modal), how, on a modal, when I hit enter I can trigger whatever action that submit has? For example right now, as they are button I have something like:
$("#btn").on("click", function(e){
e.preventDefault(); // wait... not send form yet, will be a Ajax call
});
Any help? Example code?
For reference, this is the modal content (I using with Twig as part of a Symfony2 project so don't worry about {{ }}):
<div class="modal fade " id="addNorma" tabindex="-1" role="dialog" aria-labelledby="addNorma" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">{{ 'boton.cerrar'|trans({}, 'AppBundle') }}</span></button>
<h4 class="modal-title" id="myModalLabel">{{ 'modal.normas.titulo'|trans({}, 'AppBundle') }}</h4>
</div>
<div class="modal-body">
<form id="buscadorNorma" method="POST">
<div class="spacer10"></div>
<div class="row">
<div class="col-md-5 col-lg-5 col-sm-5 col-xs-5">
<label for="codigo_norma">{{ 'modal.normas.codigo'|trans({}, 'AppBundle') }}</label>
<input type="text" class="form-control" id="codigo_norma" name="codigo_norma" placeholder="{{ 'modal.normas.codigoPlaceholder'|trans({}, 'AppBundle') }}">
</div>
<div class="col-md-5 col-lg-5 col-sm-5 col-xs-5 col-md-offset-2">
<label for="ano_publicacion">{{ 'modal.normas.anno'|trans({}, 'AppBundle') }}</label>
<input type="text" class="form-control" id="ano_publicacion" name="ano_publicacion" placeholder="{{ 'modal.normas.annoPlaceholder'|trans({}, 'AppBundle') }}">
</div>
</div>
<div class="spacer10"></div>
<div class="row">
<div class="col-md-12">
<label for="nombre_norma">{{ 'modal.normas.term'|trans({}, 'AppBundle') }}</label>
<input type="text" class="form-control" id="nombre_norma" name="nombre_norma" placeholder="{{ 'modal.normas.termPlaceholder'|trans({}, 'AppBundle') }}">
</div>
</div>
<div class="spacer10"></div>
<div class="row">
<div class="col-md-12">
<label for="procedencia_producto">{{ 'modal.normas.comite'|trans({}, 'AppBundle') }}</label>
<div class="form-group">
<div>
<select name="comite_tecnico" id="comite_tecnico" class="form-control toSelect2">
<option value="" selected="selected">{{ 'seleccioneOpcion'|trans({}, 'AppBundle') }}</option>
{% for key, item in comiteTecnico %}
<option value="{{ key }}">{{ item.nombre }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</div>
<div class="spacer5"></div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-default pull-right" disabled="disabled" id="btnBuscarNorma"><i class="fa fa-binoculars"></i> {{ 'boton.buscar'|trans({}, 'AppBundle') }}</button>
</div>
</div>
</form>
<div class="spacer10"></div>
<table class="table table-hover table-condensed" id="resultadoNorma" style="display: none">
<thead>
<tr>
<th><input type="checkbox" id="toggleCheckboxNorma" name="toggleCheckboxNorma" /></th>
<th>{{ 'columnas.normas.no'|trans({}, 'AppBundle') }}</th>
<th>{{ 'columnas.normas.norma'|trans({}, 'AppBundle') }}</th>
<th>{{ 'columnas.normas.anno'|trans({}, 'AppBundle') }}</th>
<th>{{ 'columnas.normas.comite'|trans({}, 'AppBundle') }}</th>
</tr>
</thead>
<tbody id="resultadoNormaBody"></tbody>
</table>
<div class="alert alert-danger" role="alert" style="display: none;" id="sinResultadosBuscarNormas">
{{ 'mensajes.msgNoEncontrado'|trans({}, 'AppBundle') }}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">{{ 'boton.regresar'|trans({}, 'AppBundle') }}</button>
<button type="submit" class="btn btn-primary" id="btnAplicarNorma" disabled="disabled"><i class="fa fa-save"></i> {{ 'boton.aplicar'|trans({}, 'AppBundle') }}</button>
</div>
</div>
</div>
</div>
And that's the code I trigger when I click on #btnBuscarNorma:
$('button#btnBuscarNorma').on('click', function (ev) {
ev.preventDefault();
$.post(Routing.generate('filtrarNormas'), $('#buscadorNorma').serialize(), 'json')
.done(function (data, textStatus, jqXHR) {
$('#resultadoNorma').toggle(!!data.entities.length);
$("#sinResultadosBuscarNormas").toggle(!data.entities.length);
if (data.entities.length > 0) {
var $html = '';
data.entities.forEach(function (value, index, array) {
$html += '<tr>';
$html += '<td><input type="checkbox" id="' + value.id + '" value="' + value.id + '"></td>';
$html += '<td>' + value.codigo + '</td>';
$html += '<td>' + value.norma + '</td>';
$html += '<td>' + value.anno + '</td>';
$html += '<td>' + value.comiteTecnico + '</td>';
$html += '</tr>';
});
$("table tbody#resultadoNormaBody").html($html);
marcarTodosCheck('#toggleCheckboxNorma', '#resultadoNormaBody');
}
});
});
The idea is Enter key will trigger #btnBuscarNorma click event and not #btnAplicarNorma click event.
Bind this event when you open a modal.
//to prevent multiple binding
$(document).unbind("keyup").keyup(function(e){
var code = e.which; // recommended to use e.which, it's normalized across browsers
if(code==13)
{
$("#btn").click();
}
});
You can listen for a form submit and prevent it.
$('#myform').on('submit', function (e) {
e.preventDefault();
});
This way you can make sure the form is never submitted. You can also start the Ajax call when the submit function is called.
A normal button <button> also doesn't submit the form.
When modal is opened in class is active on it.
So you can get in JQuery:
$("#addNorma.in").on("keydown",function(e){
if(e.which == 13){
//Do something.
}
});
Related
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}
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');
$('#btnAddPhysicians').click(function () {
var rowCount;
rowCount = $('#gvPhysicians tr').length;
if ($('#txtDoctorName').val() != '' && $('#gvPhysicians').length > 1) {
$('#gvPhysicians').after('<tr><td>' + rowCount + '</td>' +
'<td>' + $('#txtDoctorName').val() + '</td>' +
'<td>' + $('#txtSpecialty').val() + '</td>');
$('#divContainer').find('input:text').each(function () {
$('input:text[id=' + $(this).attr('id') + ']').val('');
}
);
}
else alert('Invalid!');
});
now I write this function in jquery but its always executing else statement "Invalid"
code for html textboxes and gridview is below
<div class="form-group">
<div class="tab-custom-content">
<label for="menu_name">Please list ALL active treating physicians (i.e. pulmonologist, oncologist, internist, cardiologist, etc)</label>
</div>
<div class=" row">
<div class="col-sm-4">
<label for="menu_name">Doctor’s Name</label>
<input type="text" class="form-control" id="txtDoctorName" name="txtDoctorName">
</div>
<div class="col-sm-4">
<label for="menu_name">Specialty</label>
<input type="text" class="form-control" id="txtSpecialty" name="txtSpecialty">
</div>
<div class="col-sm-4">
<br />
<button type="submit" id="btnAddPhysicians" class="btn btn-outline-primary">ADD</button>
</div>
</div>
<div class=" row">
<section class="content">
<div class="card">
<div class="card-header">
</div>
<!-- /.card-header -->
<div class="card-body">
<div id="gvPhysicians" class="jsgrid" style="position: relative; height: 100%; width: 200%;">
<div class="jsgrid-grid-header jsgrid-header-scrollbar">
<table class="jsgrid-table">
<tr class="jsgrid-header-row">
<th class="jsgrid-header-cell jsgrid-header-sortable" style="width: 400px;">Doctor's Name</th>
<th class="jsgrid-header-cell jsgrid-align-right jsgrid-header-sortable" style="width: 250px;">Specialty</th>
</tr>
</table>
</div>
<!-- /.card-body -->
<!-- /.card -->
</div>
</div>
</div>
</section>
</div>
<div class=" row">
<button type="submit" id="btnNext1" class="btn btn-outline-primary">Next</button>
</div>
</div>
I want to show txtDoctorName value and txtSpecialty to gridview column on click of btnAddPhysicians.I am doind this in MVC 5 and using jquery for this.
I just added Length >== 1 because it returned Length = 1 each time.
I added javascript, jquery at the bottom of my blade page to allow me to add a new line containing all the table with id="dynamic_field".(but without the button name "add" after the second, it should be a cross for deleting)
And my question is : how I can put all this these lines in $('#dynamic_field').append(....here....) because I try copy paste and there is everytime syntax error..
here the blade file:
#extends ('layout.layout')
#section('containerContent')
<div class="col-md-12">
<form method="POST" enctype="multipart/form-data" id="add_tour">
{{ csrf_field() }}
#if (count($errors))
<div class="form-group">
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li> {{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
<div class="content">
<h1>Create a new Tour:</h1>
<div class="form-group">
<div class="col-lg-6">
<input class="form-control" type="text" name="tourLabel" placeholder="Tour label">
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
<textarea class="form-control" placeholder="Resume of tour" name="tourResume" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-6">
<select id='nameArtist' name='nameArtist'>
<option value=''>Select Music Artist or Band</option>
#foreach ($artists as $artist)
<option value="{{ $artist->id }}">{{ $artist->artist_name }}</option>
#endforeach
</select>
</div>
</div>
<h2 align="center">Add Concert to your Tour:</h2>
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><select id='concertRoom' name='concertRoom'>
<option>Select your concert room</option>
#foreach ($roomsconcert as $room)
<option value="{{ $room->id }}">{{ $room->name }}</option>
#endforeach
</select>
</td>
<td><input class="form-control" type="date" name="dateConcert"{{ Form::datetime('') }}></td>
<td><input class="form-control" type="text" name="concertDuration" placeholder="Duration of the event (min)"></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More concert</button></td>
</tr>
</table>
</div>
<a class="btn btn-primary" href="{{route('show-tour') }}" > Back </a>
<button class="btn btn-success" type="submit"> {{ 'Submit' }}</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i = 1;
$('#add').click(function() {
i++;
var htmlContent = $('#dynamic_field').html();
/*
$('#dynamic_field').append(htmlContent);
*/
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click','.btn_remove',function () {
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
#endsection
thanks
Try wrapping your javascript with #verbatim Directive
#verbatim
<script type="text/javascript">
......
</script>
#endverbatim
I have this modal
<!-- Modal -->
<div id="normale" class="modal fade" role="dialog">
<div class="modal-dialog" style="background-color:white">
<!-- Modal content-->
<div class="modal-content" style="background-color:white">
<div class="modal-header" style="background-color:white">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi al carrello</h4>
</div>
<div class="modal-body" id="mod_carrello" style="background-color:white">
<div class="hidden">
<input type="text" id="id_tariffa" name="id_tariffa" value="id_tariffa" readonly class="form-control hidethis" style="display:none" >
</div>
<div class="form-group hidethis " style="display:none" >
<label for="Id" class=" control-label col-md-4 text-left"> Id </label>
<div class="col-md-6">
<input type="text" id="id" name="id">
</div>
<div class="col-md-2">
</div>
</div>
<div class="form-group hidethis " style="display:none">
<label for="Cod Carrello" class=" control-label col-md-4 text-left"> Cod Carrello </label>
<div class="col-md-6">
<?php
$persistent = DB::table('carrello')->where('entry_by', \Session::get('uid'))->first();
if (empty($persistent)) {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code = '' ;
while ($i <= 20) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$code = $code . $tmp;
$i++; } ?>
<input type="text" name="cod_carrello" value="{{ $code }}" id="cod_carrello">
<?php } else {
$cod_carrello = $persistent->cod_carrello; ?>
<input type="text" name="cod_carrello" value="{{ $cod_carrello }}" id="cod_carrello">
<?php } ?>
</div>
<div class="col-md-2">
</div>
</div>
<div class="form-group " >
<label for="Quantita" class=" control-label col-md-4 text-left"> Quantita </label>
<div class="col-md-6">
<input type="text" class="form-control" id="quantita" name="quantita">
</div>
<div class="col-md-2">
</div>
</div>
</fieldset>
</div>
<div class="modal-footer" style="background-color:white">
<button type="submit" id="add_to_cart" class="btn btn-assertive">Aggiungi</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
</div>
</div>
</div>
</div>
That is an Ajax cart.
This is the Jquery script:
$('#add_to_cart').click(function(){
var button = $(event.relatedTarget) // Button that triggered the modal
var id_tariffa = button.data('tariffa')
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.hidden input').val(id_tariffa);
var cod_carrello = document.getElementById("cod_carrello").value;
var quantita = document.getElementById("quantita").value;
$.ajax({
url: 'carrello-ajax',
type: "post",
data: {'id_tariffa':id_tariffa, 'cod_carrello':cod_carrello, 'quantita':quantita, '_token': $('input[name=_token]').val()},
success: function(data){
if ( data.OK == 1 ) {
var mod_carrello_original = $("#mod_carrello").html();
$('#mod_carrello').html('<h1 align="center" style="color:green; font-size: 21.5em;"><i class="fa fa-smile-o"></i></h1><br><br><h3 align="center">Servizio aggiunto correttamente al carrello</h3>');
$("#normale").on("hidden.bs.modal", function(){
$('#mod_carrello').html(mod_carrello_original);
});
} else {
$('#mod_carrello').html('<h1 style="color:green"><i class="fa fa-error"></i><br>Si è verificato un errore</h2>');
}
}
});
});
});
My problem is that after 2 times that I input and add to cart some product without any problem the modal no longer updates content nor shows every time the success message.
I hope that someone can help me.
Solved using a fresh div with the same content bu different id