asp.net mvc pop-up modal read from table row - javascript

I can successfully read my selected table row to my pop-up modal but if I am going to move my button to dynamic reading of table row from javascript all of my fields will become empty or did not read the selected table.
Here my Javascript that build my table row together with my button update to call pop-up modal:
$.get("/Home/GetItem", function (data) {
tempDIM = JSON.parse(data);
if (tempDIM[0]["status"] == "SUCCESS") {
for (var i = 1; i < tempDIM.length - 1; i++) {
$("#TableBody").append("<tr>" +
"<th scope='row'>" + (i + 1) + "</th>" +
"<td id='" + tempDIM[i]["id"] + "'>" + tempDIM[i]["id"] + "</td>" +
"<td>" + tempDIM[i]["name"] + "</td>" +
"<td>" + tempDIM[i]["address"] + "</td>" +
"<td>" + tempDIM[i]["age"] + "</td>" +
"<td>" + tempDIM[i]["status"] + "</td>" +
'<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Update</button></td>' +
"</tr > ");
}
}
});
Modal:
<table class="table" style="margin-top:10px">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>age</th>
<th>status</th>
</tr>
</thead>
</table>
<table class="table table-striped" id="tBody">
<tbody id="TableBody"></tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" data-target="#exampleModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"><b>Update Selected Details</b></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">
<label>id:</label>
<input type="text" id="id" disabled />
</div>
<div class="form-group">
<label>name :</label>
<input type="text" id="name" disabled />
</div>
<div class="form-group">
<label>address :</label>
<input type="text" id="address" disabled />
</div>
<div class="form-group">
<label>age:</label>
<input type="text" id="age" disabled />
</div>
<div class="form-group">
<label>status:</label>
<input type="text" id="status" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" onclick="SaveChanges()" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
And my script for reading the table:
$(function () {
$(".btn").click(function () {
var $row = $(this).closest("tr"), // Finds the closest row <tr>
$tds = $row.find("td"); // Finds all children <td> elements
$("#id").val($row.find('td:eq(0)').text())
$("#name").val($row.find('td:eq(1)').text())
$("#address").val($row.find('td:eq(2)').text())
$("#age").val($row.find('td:eq(3)').text())
$("#status").val($row.find('td:eq(4)').text())
});
});
Any suggestion or comments why I am getting null value from my pop-up modal. TIA

Assumed that your table contains proper data, $(".btn").click() event handler seems to be wrong because you may call other button with class="btn" outside the table row (i.e. <button type="button" id="btnSave" ...>). You should handle show.bs.modal event from exampleModal instead, then iterate row elements and put all values into corresponding <input> elements ordered by column index like example below:
$("#exampleModal").on('show.bs.modal', function (e) {
var $button = $(e.relatedTarget);
var $row = $button.closest("tr");
var $tds = $row.find("td");
$.each($tds, function(i, value) {
$("input:eq(" + i + ")").val($(this).text());
});
});
Note: If you want to submit textbox values inside the modal, avoid using disabled attribute which prevents the value from being posted, use readonly instead e.g. <input type="text" id="id" readonly="readonly" />.
Working example (simplified): .NET Fiddle
Related issue:
Click button on row of the table and show values in modal-window

Related

jQuery how to use event driven variable in multiple functions

I have a function that assigns values to multiple dynamically rendered input boxes based on their events. One of these values originate from a Modal, I would like to assign the value from the Modal to a textbox but am having trouble getting the value inside the Modal saving function as the value is generated in an external function. i have tried nesting or separating the two functions but I can't get it right. I would really appreciate any help.
Here is the code for the dynamic inputs in a table
<table id="requested-wh-stock-table" class="table table-bordered table-hover dataTable" width="100%">
<thead>
<tr>
<th width="50%">Luminaire</th>
<th>Shelve Number</th>
<th>Order Quantity</th>
<th>Delivered Qty</th>
<th>Back Order Qty</th>
</tr>
</thead>
<tbody>
#foreach ($salesorder as $request)
<tr>
<td>
<input type="hidden" class="wh_id" name="wh_id" value="{{$request->wh_id}}">
<input type="hidden" class="wh_id" name="light_id" value="{{$request->light_id}}">
<input type="text" class="form-control" name="luminaire" value="{{$request->luminaire}}" readonly></td>
<td><input type="text" class="form-control shelve_number" name="shelve_number" id="shelve_number" value="" onfocus="popModal(this)"></td>
<td><input type="number" class="form-control order_quantity" name="order_quantity" id="order_quantity" value="{{$request->quantity}}" readonly/></td>
<td><input type="number" class="form-control delivered_quantity" name="delivered_quantity" id="delivered_quantity" value=""/></td>
<td><input type="number" class="form-control backorder_quantity" name="backorder_quantity" id="backorder_quantity" value="" readonly/></td>
</tr>
#endforeach
</tbody>
</table>
Here is the Modal Code
<!--Shelve Modal-->
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">Select Shelve Number</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-12" style="text-align:center;margin-bottom:5%;margin-right:10%">
<div class="row">
<div class="col-sm-6">
<label>Shelve Number</label>
</div>
<div class="col-sm-6">
<select id="shelve_no" class="form-control select2" style="width: 100%;" name="shelve_no">
</select>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_modal" class="btn btn-primary">Save changes</button>
</div>
</div>
/div>
</div>
<!--End of Model-->
Here are my 2 functions
function popModal(x){
$('#myModal').modal('show');
}
//Return list of Shelves based on ordered luminaire
$('.shelve_number').on('focus',function(){
var wh_id = 1;
var light_id = 9963;
var elementChanges = "<option value='0' disabled selected>Select Shelve Number</option>";
document.getElementById('shelve_no').innerHTML = elementChanges;
$.ajax({
type:"GET",
url: '{!! url('warehouse/getshelveByluminaire') !!}/'+wh_id+"/"+light_id,
}).done(function(res) {
console.log(res);
var elems ="<option value='0' disabled selected='selected'>Choose Shelve</option>";
for(var x=0;x<res.length;x++){
elems =elems + "<option value='"+JSON.stringify(res[x])+"'>"+res[x].shelve_no+"</option>";
}
document.getElementById('shelve_no').innerHTML = elems;
});
});
//Assign Shelve number
$(document).ready(function() {
$('.shelve_number').on('change',function() {
let parent = $(this).parents('tr');
let shelve = parent.find('.shelve_number');
var selected_shelve = jQuery("#shelve_no option:selected").val();
var shelve_selected =JSON.parse(selected_shelve).shelve_no;
//Save Modal function
$('#save_modal').on('click',function(x){
shelve.val(shelve_selected);
$('#myModal').modal('hide');
});
});
});
The shelve listing function is working fine, as the shelves get listed in a drop down and I can select a shelve, but the moment I click on "Save Changes" nothing happens, and there is nothing in the Console. Please assist, I am having trouble with the last 2 functions enter image description here
You can make the variables global using window.
function popModal(x){
$('#myModal').modal('show');
}
$('.shelve_number').on('focus', function() {
let parent = $(this).parents('tr');
window.shelve = parent.find('.shelve_number');
var wh_id = 1;
var light_id = 9963;
var elementChanges = "<option value='0' disabled selected>Select Shelve Number</option>";
$('#shelve_no').html(elementChanges);
$.ajax({
type: 'GET',
url: "{!! url('warehouse/getshelveByluminaire') !!}/" + wh_id + "/" + light_id
}).done(function(res) {
console.log(res);
var elems = "<option value='0' disabled selected='selected'>Choose Shelve</option>";
for (var x = 0; x < res.length; x++) {
elems = elems + "<option value='" + JSON.stringify(res[x]) + "'>" + res[x].shelve_no + "</option>";
}
$('#shelve_no').html(elems);
});
});
//Assign Shelve number
$(document).ready(function() {
//Save Modal function
$('#save_modal').on('click',function(x) {
var selected_shelve = jQuery("#shelve_no option:selected").val();
var shelve_selected = JSON.parse(selected_shelve).shelve_no;
shelve.val(shelve_selected);
$('#myModal').modal('hide');
});
});

The old value always retain in the textbox modal popup and Can't get the fresh value

I know that there is a lot solution on my problem and I tried some of them,
I also tried this one
$('#myModal').on('hidden.bs.modal', function () {
$('.modal-body').find('textarea,input').val('');
});
but not working
and I even tried this code $('.modalclass').remove();
and also this one $("#myModal")[0].reset();
<div class="container">
<h2>Employees Record</h2>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Employee</button><br /><br />
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Age
</th>
<th>
State
</th>
<th>
Country
</th>
<th>
Action
</th>
</tr>
</thead>
<tbody class="tbody">
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" 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">×</button>
<h4 class="modal-title" id="myModalLabel">Add Employee</h4>
</div>
<div class="modal-body" id="hello">
<form>
<div class="form-group">
<label for="EmployeeId">ID</label>
<input type="text" class="form-control" id="EmployeeID" placeholder="Id" disabled="disabled"/>
</div>
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="Name" placeholder="Name"/>
</div>
<div class="form-group">
<label for="Age">Age</label>
<input type="text" class="form-control" id="Age" placeholder="Age" />
</div>
<div class="form-group">
<label for="State">State</label>
<input type="text" class="form-control" id="State" placeholder="State"/>
</div>
<div class="form-group">
<label for="Country">Country</label>
<input type="text" class="form-control" id="Country" placeholder="Country"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
<button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
here's my Script code
//function for updating employee's record
function Update() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
EmployeeID: $('#EmployeeID').val(),
Name: $('#Name').val(),
Age: $('#Age').val(),
State: $('#State').val(),
Country: $('#Country').val(),
};
$.ajax({
url: "/Home/Update",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
loadData();
$('#myModal').modal('hide');
window.location.reload();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
this is my fuction for clearing the textbox box but it miraculously not working on the edit/updated button.
//Function for clearing the textboxes
function clearTextBox() {
$('#EmployeeID').val("");
$('#Name').val("");
$('#Age').val("");
$('#State').val("");
$('#Country').val("");
$('#btnUpdate').hide();
$('#btnAdd').show();
}
And this is for my edit and delete
//Load Data function
function loadData() {
$.ajax({
url: "/Home/List",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.EmployeeID + '</td>';
html += '<td>' + item.Name + '</td>';
html += '<td>' + item.Age + '</td>';
html += '<td>' + item.State + '</td>';
html += '<td>' + item.Country + '</td>';
html += '<td>Edit | Delete</td>';
html += '</tr>';
});
$('.tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}

Get ID of Table Element and open a modal with data with same id

Hy,
i have the following table with bootstrap that have data from php select:
<div class="table-responsive">
<table class="table table-bordered table-hover">
<tr>
<th>Nome</th>
<th>Cognome</th>
<th>Telefono</th>
<th>E-mail</th>
<th>Azioni Utente</th>
<tr>
<?php
while($contatto = mysql_fetch_assoc($risultati)) {
echo "<tr>";
echo "<td>" .$contatto['nome']. "</td>";
echo "<td>" .$contatto['cognome']. "</td>";
echo "<td>" .$contatto['telefono']. "</td>";
echo "<td>" .$contatto['email']. "</td>";
echo "<td>
<a href='#' class='btn btn-primary' data-id='".$id = $contatto['id']."'><span class='glyphicon glyphicon-pencil'></span></a></button>
</td>";
}
?>
</table>
</div>
And clicking on button open me this modal:
<div id="myModal" class="modal fade" style="padding-top:15%; overflow-y:visible;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
<h4 class="modal-title custom_align" id="Heading">Modifica Dati Contatto</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input class="form-control" type="text" placeholder="Nome" value = "<?php echo $row[0]; ?>">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="Cognome">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="Riferimento (Eventuale)">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="Numero Telefono">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="Indirizzo E-mail">
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-primary btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Modifica Contatto</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
with this javascript:
<script type="text/javascript">
$(document).ready(function(){
$('.btn').click(function(){
//get id
var id = $(this).data('id');
$("#myModal").modal('show');
});
});
</script>
i want know what is the best solution to open the modal with the values ​​of sql's row with same id.
thanks in advance for any suggestions
I would use an AJAX call when the button gets pressed. Something such as:
<script type="text/javascript">
$(document).ready(function() {
$('.btn').click(function() {
//get id
var id = $(this).data('id');
$.ajax({
url: "lookup.php",
data: id,
type: "POST",
cache: false,
dataType: "json"
}).done(function(response) {
// do error checking, etc.
if (response) {
$("#myModal").modal('show');
}
});
});
</script>
Then from here if you return any data from the database you can append them to the modal using jQuery.

Fill form with table row data using javascript

I am having trouble filling a form with table data.The form is in a modal dialogue and I want the dialogue to popup with inputs filled when the user clicks on the glyphicon, glyphicon-pencil.
I have looked at Fill form using table data, How to fill input fields in form with data from row in html table I want to edit, jQuery dynamic fill in form fields with table data, and Automatic fill a table with data using JavaScript and JSON, and none of their solutions worked for me, so please help.
here is the modal and form code:
<div class="modal fade" id="New-Employee-Modal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Employee</h4>
</div>
<div class="modal-body">
<div id="data">
<form id="person">
<div class="form-group">
<label class="control-label">First Name:</label>
<input class="form-control" id="FirstName" name="FirstName" type="text">
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input class="form-control" id="LastName" name="LastName" type="text">
</div>
<div class="form-group">
<label class="control-label">Net Id:</label>
<input class="form-control" id="NetId" name="Netid" type="text">
</div>
<div class="form-group">
<label class="control-label">Phone #:</label>
<input class="form-control" id="PhoneNumber" name="PhoneNumber" type="tel" required />
</div>
<div class="form-group">
<label class="control-label">Email:</label>
<input class="form-control" id="Email" name="Email" type="text">
</div>
<div class="form-group">
<label class="control-label">Role</label>
<input class="form-control" id="Role" name="Role" type="text">
</div>
<div class="form-group">
<label class="control-label">Active:</label>
<br />
<input name="Active" type="radio" value='<span class="glyphicon glyphicon-ok-circle">' /> Active
<br />
<input name="Active" type="radio" value='<span class="glyphicon glyphicon-ban-circle">' /> Not Active
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="ResetForm()">Reset</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="AddData()">Save</button>
</div>
</div>
</div>
</div>
Here is the part of the table:
<div id="tab">
<table class="table table-striped" id="list">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Net ID</th>
<th>Phone #</th>
<th>Email</th>
<th>Active</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Joel</td>
<td>lewis</td>
<td>lewisj</td>
<td>333-555-3667</td>
<td>lewisj#gmail.com</td>
<td>
<a id="icon-toggle" class="btn-default">
<span class="glyphicon glyphicon-ok-circle" aria-hidden="true"></span>
</a>
</td>
<td>Developer</td>
<td>
<span class="glyphicon glyphicon-pencil" data-target="#New-Employee-Modal" onclick="UpdateForm()" aria-hidden="true"></span>
<a id="icon-toggle-delete" class="removebutton">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</a>
</td>
</tr>
and here is the javascript:
function AddData() {
var rows = "";
var FirstName = document.getElementById("FirstName").value;
var LastName = document.getElementById("LastName").value;
var NetId = document.getElementById("NetId").value;
var PhoneNumber = document.getElementById("PhoneNumber").value.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
var Email = document.getElementById("Email").value;
var Active = document.querySelector('input[name="Active"]:checked');
Active = Active ? Active.value : '';
var Role = document.getElementById("Role").value;
rows += "<td>" + FirstName + "</td><td>" + LastName + "</td><td>" + NetId + "</td><td>" + PhoneNumber + "</td><td>" + Email + "</td><td>" + Active + "</td><td>" + Role + '</td><td> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> <a id="icon-toggle-delete2" class="removebutton"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </a></td>';
var tbody = document.querySelector("#list tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
function UpdateForm() {
$('span.glyphicon glyphicon-pencil').click(function() {
//! Don't know what do here
});
}
function ResetForm() {
document.getElementById("person").reset();
}
here is the jsfiddle http://jsfiddle.net/neu4gh37/2/
You can use such an example of code. Note, you don't need call UpdateForm() with onclick event, you added this event by jQuery for the selector 'span.glyphicon-pencil' (I fixed it a little)
$('span.glyphicon-pencil').click(function () {
var formFields = [];
var $target = $(event.target);
var $row = $target.closest('tr');
$row.find('td').each(function (index, el) {
var fieldValue = $(el).html();
switch (index) {
case 0:
formFields['FirstName'] = fieldValue;
break;
case 1:
formFields['LastName'] = fieldValue;
break;
default:
break;
}
});
fillForm(formFields);
});
function fillForm(data) {
var $form = $('#person');
$form.find('input').each(function () {
var $input = $(this);
switch ($input.attr("name")) {
case 'FirstName':
$input.val(data['FirstName']);
break;
case 'LastName':
$input.val(data['LastName']);
break;
default:
break;
}
});
}

Trigger onClick event when Enter keypress in a Twitter Bootstrap Modal

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.
}
});

Categories