JavaScript for each record in my view - javascript

I have a VIEW where I display a table with 15 records (15 rows) and 5 columns, but the very thing that matters is a column, "Actions". In it I have 1 button, "Preview", that when clicking, I want to open a window with a message, for tests.
However, only the first record, when clicking the "View" button, displays the message window, the other 14 records do not.
How do I make all records / lines display the message?
Follow the code below:
<table class="table table-bordered table-hover tablesorter">
<thead>
<tr>
<th class="header text-center" style="width: 100px;"> Ações </th>
</tr>
</thead>
<tbody id="tabela">
#foreach (var item in Model)
{
<tr>
<td>
#this.Hidden("IdClient").Value(item.Id)
<a id="visualizarCliente" class="btn btn-primary btn-xs btn-visualizar" data-toggle="tooltip" title="Visualizar" target="_blank"
href="#Url.Action(MVC.Painel.Clientes.Visualizar(item.Id))">
<i class="fa fa-eye"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(function () {
$("#visualizarCliente").click(function () {
var idCliente = $("#IdClient").val();
window.alert("Teste");
})
});
</script>

The problem is that you are using the id selector and it can not be repeated. Switch to any other selector, such as data-toggle = "tooltip" for example.
<script type="text/javascript">
$(function () {
$("a[data-toggle='tooltip']").click(function () {
window.alert("Teste");
})
});
</script>

The problem is ID which always be used for something UNIQUE. Try to use CLASS instead. Your function should goes something like this one example:
$(function () {
$(".btn-visualizar").click(function () {
var idCliente = $(this).parent().find("#IdClient").val();
window.alert("Teste");
})
});
In the given example the line $(this).parent().find("#IdClient").val(); specifies that this would be it's nearest element value as it should be.

Related

bootstrap modal displays twice

I have a users table with a button that shows a modal containing info about the user.
So I will have 10 rows, each with its own button, the first time I press a button, it will display a modal (let's call this modal A) containing the info for the user and work normally.
When I click on a button for another user it will display modal A then on top it will display the correct modal (modal B) when I close this modal, modal A is no longer on screen but the backdrop will still be visible.
I'm using laravel 5.5 with bootstrap 3 here is the code for the modal load.
Javascript
$(".btn").click(function(){
var button = $(this)
var employee_id = button.data('id')
var url = "/something/else/" + employee_id;
$('.modal-container').load(url,function(result){
$('#display').modal({show:true});
});
});
HTML
<a class="btn btn-primary" data-toggle="modal" data-id="{{ $simething->id }}" href="#display" id="modal_link">Show Modal</a>
This is the complete code
<table id="table" class="table" cellspacing="0" width="100%" role="grid">
<thead>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Events</th>
</thead>
<tbody>
#foreach ($empleados as $empleado)
<tr>
<td>{{ $simething->id }}</td>
<td>{{ $simething->fname }}</td>
<td>{{ $simething->lname }}</td>
<td>
<a class="btn btn-primary" data-toggle="modal" data-id="{{ $simething->id }}" href="#display" id="modal_link">Show Modal</a>
<div class="modal-container"></div>
</td>
</tr>
#endforeach
</tbody>
<script>
$(document).ready(function(){
$(".btn").on('click', function(e){
var button = $(this); // Button that triggered the modal
var employee_id = button.data('id'); // Extract info from data-* attributes
var url = "/somethin/else/" + employee_id;
$('.modal-container').load(url,function(){
$('#display').modal('show');
});
});
});
</script>
You are launching the modal twice every time, which after a few clicks is probably stacking up and causing the issues you're seeing. Try changing your html to not auto launch a modal, like so:
<a class="btn btn-primary modal-btn" data-id="{{ $simething->id }}" href="#/" id="modal_link">Show Modal</a>
Also, you shouldnt use the ".btn" as the way you select the button, as many buttons on your page may have that boostrap class. I would give it a unique class that you only want to target this modal with, or an ID if its for only one button per click event. Change your javascript to this:
$(".modal-btn").click(function(){
var button = $(this)
var employee_id = button.data('id')
var url = "/something/else/" + employee_id;
$('.modal-container').load(url,function(result){
$('#display').modal({show:true});
});
});

jQuery : Trigger event on dynamic content

i am trying to use the dynamic table at
https://codepen.io/ashblue/pen/mCtuA
I want to have a button that deletes all rows from the table. SO basically, fire the click function on all instances of the class .table-remove
i tried to do the following
function deleteAll() {
jQuery('.table-remove').each(function() {
var currentElement = $(this);
console.log(currentElement);
currentElement.trigger('click');
});
}
where the click is defined as
$('.table-remove').click(function() {
console.log("triggered");
$(this).parents('tr').detach();
});
but nothing happens when i call the deleteAll function. i dont even se anything on the console
am i doing this right?
I want to have a button that deletes all rows from the table. So basically, fire the click function on all instances of the class .table-remove.
You could do it that way but it's far simpler to organise your table into :
a <thead> containing the header row
a <tbody> containing the visible row(s)
a <tbody> containing the row template
Thus, the code behind the "Delete All" button can very simply select all rows in the first <tbody> and .remove() them.
HTML
<div class="container">
<h1>HTML5 Editable Table</h1>
<p>Through the powers of <strong>contenteditable</strong> and some simple jQuery you can easily create a custom editable table. No need for a robust JavaScript library anymore these days.</p>
<ul>
<li>An editable table that exports a hash array. Dynamically compiles rows from headers</li>
<li>Simple / powerful features such as add row, remove row, move row up/down.</li>
</ul>
<div id="table" class="table-editable">
<span class="table-add glyphicon glyphicon-plus"></span>
<table class="table">
<thead> <!-- <<<< wrap the header row in <thead>...</thead> -->
<tr>
<th>Name</th>
<th>Value</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody class="main"> <!-- <<<< wrap the visible row(s) in <tbody>...</tbody> -->
<tr>
<td contenteditable="true">Stir Fry</td>
<td contenteditable="true">stir-fry</td>
<td>
<span class="table-remove glyphicon glyphicon-remove"></span>
</td>
<td>
<span class="table-up glyphicon glyphicon-arrow-up"></span>
<span class="table-down glyphicon glyphicon-arrow-down"></span>
</td>
</tr>
</tbody>
<tbody class="hide"> <!-- <<<< wrap the template row in its own hidden <tbody>...</tbody> -->
<tr>
<td contenteditable="true">Untitled</td>
<td contenteditable="true">undefined</td>
<td>
<span class="table-remove glyphicon glyphicon-remove"></span>
</td>
<td>
<span class="table-up glyphicon glyphicon-arrow-up"></span>
<span class="table-down glyphicon glyphicon-arrow-down"></span>
</td>
</tr>
</tbody>
</table>
</div>
<button id="export-btn" class="btn btn-primary">Export Data</button>
<button id="deleteAll-btn" class="btn btn-primary">Delete All</button>
<p id="export"></p>
</div>
Another aspect is how best to attach click handlers to the three row actions - delete, move-up and move-down.
As the rows are created/appended dynamically, the way to go is to delegate click handling to a container (eg the table) using jQuery's $(static-container).on(event, descendent-selector, handler). This will attach the desired actions to all current rows, and future rows just by appending them.
Javascript
jQuery(function($) {
var $TABLE = $('#table table');
var $BTN = $('#export-btn');
var $BTN2 = $('#deleteAll-btn');
var $EXPORT = $('#export');
$('.table-add').on('click', function() {
$('tbody.hide tr', $TABLE).clone(true).appendTo($('tbody.main', $TABLE));
});
$TABLE.on('click', '.table-remove', function() { // delegate row removal to the table
$(this).closest('tr').remove();
});
$TABLE.on('click', '.table-up', function() { // delegate row-up movement to the table
var $row = $(this).closest('tr');
$row.insertBefore($row.prev());
});
$TABLE.on('click', '.table-down', function() { // delegate row-down movement to the table
var $row = $(this).closest('tr');
$row.insertAfter($row.next());
});
$BTN.on('click', function() {
var $headers = $('thead th', $TABLE).not(':empty').map(function() {
return $(this).text().toLowerCase();
});
var $data = $('tbody.main tr', $TABLE).map(function() {
var $td = $(this).find('td'),
h = {};
$headers.each(function(i, header) {
h[header] = $td.eq(i).text();
});
return h;
});
$EXPORT.text(JSON.stringify($headers.get().concat($data.get())));
});
$BTN2.on('click', function deleteAll() {
$("tbody.main tr", $TABLE).remove();
});
});
DEMO.
If the goal is just to remove the rows, you can do that directly without triggering each individual click event:
function deleteAll() {
$('.table-remove').closest('tr').remove()
}
If you really need to trigger the click event on each '.table-remove' element, you would do that like so:
function deleteAll() {
$('.table-remove').each(function() {
$(this).trigger('click')
});
}
(...which is roughly equivalent to your existing code. I'm not sure why your existing code isn't working for you; perhaps it's down to your use of jQuery() instead of the $() alias, or you're just not calling the deleteAll() function successfully?)

Rails+jQuery: Get the Value of an Item Inside a Table to Use in a Prepend Function

Say I have a table:
<table class="table table-bordered table-hover employes_list_panel">
<thead>
<tr>
<th></th>
<th></th>
<th class="center">Name <i class="fa fa-angle-double-down"></i></th>
<th class="center">IQ <i class="fa fa-angle-double-down"></i></th>
<th class="center">Efficiency <i class="fa fa-angle-double-down"></i></th>
<th class="center">Focus <i class="fa fa-angle-double-down"></i></th>
<th class="center">Happiness <i class="fa fa-angle-double-down"></i></th>
<th class="center">Quality <i class="fa fa-angle-double-down"></i></th>
<th class="center">Salery <i class="fa fa-angle-double-down"></i></th>
</tr>
</thead>
<tbody>
<%Employe.where(company_id: company.id, request: false).each do |employe|%>
<tr>
<td class="center cd-popup-trigger" id="popup3"><i style="color: red;" class="fa fa-close"></i></td>
<td class="center cd-popup-trigger" id="popup4"><i style="color: green;" class="fa fa-arrow-up"></i></td>
<td class="center"><%=employe.name%></td>
<td class="center"><%=employe.iq%></td>
<td class="center"><%=employe.efficiency%></td>
<td class="center"><%=employe.focus%></td>
<td class="center"><%=employe.happiness%></td>
<td class="center"><%=employe.quality.capitalize%></td>
<td class="center"><%=employe.salery%></td>
</tr>
<%end%>
</tbody>
</table>
And I want to get the value of the employe name <%=employe.name%> when popup3 for example is clicked. Note there can be more than one "employe" in the list. How can I get the value of the employe that is on the line where the user clicked the popup, so that I can prepend it using jQuery into the popup <p>.
Ex:
Click to Open Popup | Kevin |...
Click to Open Popup | Sam |...
I need to get the value Sam when I click the "second popup", the
problem is all popups currently have the same id.
Thank you.
Given your code, popup3 (and popup4 for that matter) is gonna be present multiple times on the page (once per tr). You need to give it a class, not an id. I personally like to prefix my JavaScript classes (not used for styling) with js-. In your HTML:
<td class="center cd-popup-trigger js-popup3"><i style="color: red;" class="fa fa-close"></i></td>
You also need to identify the cells which contain the employee name (you'll see why later).
<td class="center js-employee-name"><%= employe.name %></td>
In your JS code, you first need to select the all the td with the js-popup3 class:
$('js-popup3')
Then, you want to trigger something when an event occurs on the element you selected. With jQuery, you would do it like this:
$('js-popup3').on('click', function() {});
Lastly, you want to describe what should be done when the event occurs. This is done in the callback function.
$('.js-popup3').on('click', function() {
# employeeName is the value you want
employeeName = $(this).siblings('.js-employee-name').text();
});
I invite you to read a lot about JS (try to code without jQuery first). Once you feel confident with it, start looking at jQuery.
You can create a click function for the Table tr's and get the value of the third column (index 2):
$('table.reference.notranslate tbody').delegate("tr", "click", function(){
var YourEmployeName = $(this).find('td').eq(2).text();
alert(YourEmployeName);
});
To make the popups ahve unique id's according to employee try something like this:
">
Then I presume you have some js somewhere to handle the popup clicks. This js can extract the employee id with
emp_id = my_clicked_popup_trigger.attr("id").split('-')[-1]

table column hover load separate div

I'm having a bit of trouble figuring something simple out. I have a large datatable, and I want that when hovering any column, a specific div (and different for each column) is loaded somewhere on the page, outside the table.
How should I go about that? I'm having trouble defining columns (I'm using jquery dataTables), and then finding a way to load a different image for each column.
Here is my current code that doesn't take columns into account:
$('td').hover(function() {
var myClass = $(this).attr("class");
/* hide any previously loaded div */
$(".loaded").hide();
/* load my new div with the content I need */
$("#"+myClass).show();
});
And the HTML:
<thead>
<tr>
<th class="sp1">SP1</th>
<th class="sp2">SP2</th>
<th class="bb1">BB1</th>
<th class="br1">BR1</th>
<th class="br2">BR2</th>
<th class="br3">BR3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="sp1">xxx</td>
<td class="sp2">xxx</td>
<td class="bb1">xxx</td>
<td class="br1">xxx</td>
<td class="br2">xxx</td>
<td class="br3">xxx</td>
</tr>
....
</tbody>
Thanks!
Im not sure if this is what you want, but check it out:
This code will show the name of the div you are hovering in another div.
https://jsfiddle.net/5jy071t5/4/
HTML
<ul>
<li name="first">Hoover me</li>
<li name="second">And me</li>
</ul>
<div id="output"></div>
Javascript
$( "li" ).hover(
function() {
$("#output").html($(this).attr("name"));
//you can also load an image if you like
}, function() {
$("#output").html("");
}
);
It works as charm. Maybe you were missing either id or class.
$('td').hover(function() {
var myClass = $(this).attr("class");
/* hide any previously loaded div */
$(".loaded").hide();
/* load my new div with the content I need */
$("#"+myClass).show();
});
.loaded{
display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th class="sp1">SP1</th>
<th class="sp2">SP2</th>
<th class="bb1">BB1</th>
<th class="br1">BR1</th>
<th class="br2">BR2</th>
<th class="br3">BR3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="sp1">xxx</td>
<td class="sp2">xxx</td>
<td class="bb1">xxx</td>
<td class="br1">xxx</td>
<td class="br2">xxx</td>
<td class="br3">xxx</td>
</tr>
</tbody>
</table>
<div id="sp1" class="loaded">sp1</div>
<div id="sp2" class="loaded">sp2</div>
<div id="bb1" class="loaded">bb1</div>
<div id="br1" class="loaded">br1</div>
<div id="br2" class="loaded">br2</div>
<div id="br3" class="loaded">br3</div>

how to push table selections to array: jquery

Summary: I have a html page which consists of two add buttons and two tables. When add button is clicked, rows are appended to respective table. In the back end i want to collect all the row elements when "button" is clicked and POST to other page.
<div class="report">
<div class="panel">
<div>
<button type="button" class="add btn btn-primary" data-toggle="tooltip" title="Add to configuration list.">
<i class="fa fa-plus"></i>
Add
</button>
</div>
<div class ="configuration-table panel-body">
<table class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>Remove</th>
<th>Layer</th>
<th>Display</th>
<th>Unit</th>
<th>Dataset</th>
<th>Ordering</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class = "done">
<input class="btn btn-success" formaction="{% url 'something' %}" formmethod="post" type="submit" value="Done"></input>
</div>
</div>
and here is reports.js
var arr = [];
$('.report')
.on('click','.add', function(){
$(this)
.parents('.report')
.find('.configuration-table tbody')
.append(
'<tr>'+
'<td class="remove-row" role="button" aria-label="Remove Region"><i class="fa fa-times" title="Remove this row." data-toggle="tooltip" data-placement="right" aria-hidden="true"></i></td>'+
'<td>'+layer_text+'</td>'+
map_elements+
'<td>'+unit_text+'</td>'+
'<td>'+dataset_text+'</td>'+
'<td class="ordering" aria-label="Re-order"><i class="fa fa-arrows" title="Re-arrange row order." data-toggle="tooltip" data-placement="right"></i></td>'+
'</tr>'
)
.on('click','.remove-row',function() {
$(this).parents('tr').remove();
})
.sortable({
helper: script
})
.disableSelection();
.on('submit','.done form',function(){
//do domething to collect columns
$('.configuration-table tbody').each(function(){
arr.push({
column.name: column.value
});
});
})
Here as you can see that table rows can be removed/sortable. Dont worry about POST method now. I just need the logic to collect columns from the table after done button is clicked.
Assume script is correct in terms of class names and traversal-filters. I just need the logic to collect column elements and push to "arr".
Thanks in advance
Firstly, you need to loop over the th elements within the thead to get the column names, then the tr in the tbody to get the values. You can get the text() properties from each respective td to fill object. Try this:
.on('submit','.done form',function() {
var arr = [];
var $table = $('.configuration-table');
var columnNames = $table.find('thead th').map(function() {
return $(this).text();
});
$table.find('tbody tr').each(function(){
var rowValues = {};
$(this).find('td').each(function(i) {
rowValues[columnNames[i]] = $(this).text();
});
arr.push(rowValues);
});
});
Example fiddle

Categories

Resources