I have a table where I want to show the last column only if the column before is hovered. The table data is parsed with JSON.
<script type="text/javascript">
$( document ).ready(function() {
var tag_id = $('#tag_id_hidden').val();
$.getJSON("/tags/get_who_tagged/" + '{{tag.tag_id}}' + "/", function(data) {
var lines = '';
for (var i = 0; i < data.length; i++) {
lines += '<tr id="' + data[i]['entity_id'] + '">';
lines += '<td id="button_id"><button id="prefix_' + data[i]["entity_id"] + '" class="js-programmatic-set-val" value="' + data[i]["entity_id"] + '" name="' + data[i]["title"] + '"><i class="fa fa-plus"></i></button></td>';
lines += '<td>' + data[i]['title'] + '</td>';
lines += '<td id="hover_' + data[i]["entity_id"] + '">' + data[i]['count'] + '</td>';
lines += '<td id="hidden_' + data[i]["entity_id"] + '" style="display:none;">'
for (var j = 0; j < data[i]['usernames'].length; j++) {
lines += data[i]['usernames'][j]['username'] + ', '
}
lines += '</td>';
lines += '</tr>';
//$("#count_user_table").empty();
$('#count_user_table tbody').html(lines);
}
});
});
</script>
<script>
$(document).on("mouseenter", "#hover_9242411", function() {$("#hidden_9242411").show();
});
$(document).on("mouseleave", "#hover_9242411", function() {$("#hidden_9242411").hide();
});
</script>
in the example above the code is working but I have to reference the id as "#hover_9242411" and "#hidden_9242411". the part after hover_/hidden_ is dynamically added to each column with a for loop. How can I dynamically reference the second part (9242411)?
Consider modifying your hover cell to something like this:
'<td id="hover_' + data[i]["entity_id"] + '" class="hover-cell" data-target="#hidden_' + data[i]["entity_id"] + '">'
You could then simply use:
$(document).on("mouseover", ".hover-cell", function() {
var target = $(this).data('target');
$(target).show();
});
Fiddle
If it will always be the previous column showing/hiding the next column, you could write your event handlers like this
$('#mytable').on('mouseenter', 'td.hover-column', function(){
$(this).next().show();
}).on('mouseleave', 'td.hover-column', function(){
$(this).next().hide();
});
For that example to work you would need to add a class to the hover column (the one that you want to hover over in order to show the next column). I also gave an id to the table and assigned the event handler to it so the event doesnt have to bubble all the way to the top.
Here is a fiddle
If later on you find that you arent showing/hiding the NEXT column but some other one, you could also put a specific class on that hidden column and instead of using
$(this).next().show();
you could use something like
$(this).closest('tr').find('td.hidden-column').show();
Related
I have a data coming from the database. And Displaying when the ajax function is called. I am able to display it. But, One of the variable is an array data and saved it using implode function. Data is like (a,b,c,d).
Data is displaying in the below format
data1 Data2 Data3 (a,b,c,d) Data5 and so on.
I want to explode the array data and print one below the another.
I should display it like
data1 data2 data3 a data5
b
c
d
Here is the code which i am written to get the data.
<script type="text/javascript">
$('#genreport').on('click',function(){
var Representativeid = document.getElementById("Representativeid").value;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var url = '{{URL::to('/admin/GenReport')}}';
$.ajax({
type : 'get',
url : url,
data : {Representativeid:Representativeid,dateFrom:dateFrom,dateTo:dateTo},
success:function(data){
console.log(data);
var $tabledata = $('#tbody');
$tabledata.empty();
for (element in data)
{
var row = '<tr>' +
'<td>' + data[element].date + '</td>'+
'<td>' + data[element].doctor_name + '</td>'+
'<td>' #foreach(explode(',', data[element].products ) as $product)
{{$product}}
#endforeach '</td>' +
'<td>' + data[element].quantity + '</td>'+
'<td>' + data[element].locations +'</td>'+
'<td>' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row);
}
},
error:function(data)
{
alert('fail');
alert(data);
}
});
});
</script>
I am failing in the for-each logic. Please help me to display as i expected.
You cannot use a php function/code(server-side) in your javascript/jQuery code(client-side), as the php code will be parsed before the page is loaded. Instead you need to use javascript code.
First, you need to split the value into an array
var productsArray = data[element].products.split(',');
then you would need to get the array count (.length) to use a rowspan, so it doesn't break your table stucture
var rowSpan = productsArray.length;
....
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
....
finally, you need to loop in javascript, not php, through the array. (note, because the i<0 <td>s go on subsequent rows, you need to add them after)
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
so it would look something like this -
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
// get products array count
var rowSpan = productsArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td></tr>';
}
}
row +=
'<td rowspan="'+rowSpan+'">' + data[element].quantity + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].area + '</td>'+
'</tr>';
// append both row and the <td>s in rowAfter
$('#tbody').append(row+rowAfter);
}
just add <tr><td> inside foreach.
Edit:
Also, take a look at this link. table inside a td
Hi people i have a dynamic table (add rows from ajax requests) and i need sum and multiply values always (without a trigger event).
i have already a functions that make it with the event (blur) but i don't wanna make it by using the blur trigger.
There is a way for do it?
My code:
$.fn.sumValues = function() {
var sum = 0;
this.each(function() {
if ($(this).is(':input')) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
});
return sum;
};
function totaliza() {
var total_recep = $('input[name^="costot"]').sumValues();
$('#total_art').val(total_recep);
}
var counter = 0;
$(document).on('click', '#bt_add', function(e) {
counter++;
var tr = '<tr id="art_' + counter + '">';
tr = tr + '<td><button name="del_art' + counter + '" id="del_art' + counter + '" class="btn btn-default btn-xs del_art" type="button">DEL</button></td>';
tr = tr + '<td><input name="cbarra' + counter + '" id="cbarra' + counter + '" class="form-control" value="02020202" readonly></td>';
tr = tr + '<td><input name="art' + counter + '" id="art' + counter + '" class="form-control" value="ARTICULO" readonly></td>';
tr = tr + '<td><select name="und' + counter + '" id="und' + counter + '" class="form-control list"></select></td>';
tr = tr + '<td><input name="cal' + counter + '" id="cant' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="cal' + counter + '" id="costou' + counter + '" class="form-control numeric cal" value="0"></td>';
tr = tr + '<td><input name="costot' + counter + '" id="costot' + counter + '" class="form-control cal" readonly value="0"></td>';
tr = tr + '</tr>';
$("#inv_recep_det tbody").append(tr);
$('.form-control').change(function() {
var number = this.name.replace('cal', '');
var costot = ($('#cant' + number).val() * $('#costou' + number).val())
$('input[name^="costot' + number + '"]').val(costot);
totaliza();
});
$('.del_art').click(function() {
var number = this.name.replace('del_art', '');
$('#art_' + number).remove();
totaliza();
});
});
https://jsfiddle.net/JuJoGuAl/kpLs9zcg/
Something like that?
http://jsfiddle.net/JuJoGuAl/0vx64u2y/
Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/
I have a table that I have dynamically created from a JSON object I am getting from the server via an ajax request. I am trying to append buttons to the end of each of the rows in the table. The table has seven rows, thus I have 7 buttons. I want something like the following. I want to set a javascript variable to create each individual button with the following parameters :
(obviously with different ids)
<input type="button"id="submit-button2"class="btn btn primary"value="Submit" />
so that I can set up an array of buttons of these variables in javascript such as the following:
var buttons = [
button1,
button2,
button3,
button4,
button5,
button6,
button7
];
Then I can iterate through my JSON object and the buttons array appending them to the table (named requestTable) like the following :
for(var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
$("<tr>" + "<td id=\"Departments\">"
+ request[0].DepartmentApprovals[j].Department +":" + "</td>"
+ "<td input type=\"text\" id=\"ApproverLanId\" contenteditable=\"false\" class=\"underline\">"
+ request[0].DepartmentApprovals[j].Approver.LanId + "</td>"
+ "<td>" + "Date:" + "</td>"
+ "<td contenteditable=\"false\" class=\"underline\">" + request[0].DateApproved + "</td>"
+ "<td>" + buttons[j].outerHTML + "</td>"+ "</tr>").appendTo("#requestTable");
}
The table data works, My issue has been that I am able to get a button to append and show if I use the document.getElementById of an existing button already created elsewhere on the form, but clearly I do not want this, I want them dynamically created with differing ids that exist only in the scope of the table. I am not sure how to accomplish this through javascript.
I am not 100% sure if this is what you want, but this code should add a button with a dynamic ID (submit-button-1, submit-button-2, etc ...) inside the last cell of each row:
for (var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
var appendHTML = '';
appendHTML += '<tr>';
appendHTML += '<td id="Departments">' + request[0].DepartmentApprovals[j].Department + ':</td>';
appendHTML += '<td input type="text" id="ApproverLanId" contenteditable="false" class="underline">' + request[0].DepartmentApprovals[j].Approver.LanId + '</td>';
appendHTML += '<td>Date:</td>';
appendHTML += '<td contenteditable="false" class="underline">' + request[0].DateApproved + '</td>';
appendHTML += '<td><input type="button" id="submit-button-' + (j + 1) + '" class="btn btn primary" value="Submit" /></td>';
appendHTML += '</tr>';
appendHTML.appendTo('#requestTable');
}
try this
var button = document.createElement("button");
button.innerHTML ="/*put name of button here*/";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function(){/*put what button does here*/}
I have a loop which is creating table:
for(m=1; m<7; m++){
document.getElementById('content').innerHTML +=
('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>')
}
In every row in second TD is button which must be assigned to every row. Each button has his own row. I want to alert m from the first TD exactly when i click button from that row. I mean if i will click button is switch2 i will get alert from m "2".
Here is the button code i tried:
var buttons = "#switch" + m
$(function() {
$(buttons).button();
$(buttons).click(function(){
alert(m);
});
});
This is not working because all of the buttons alerting last value from loop = 6.
I know it is confused but i hope you uderstand. Really appreciate your help
Change it to this:
$(function() {
var localM = m;
$(buttons).button();
$(buttons).click(function(){
alert(localM);
});
});
The problem is the alert binds to the variable m not the value of m. By allocating a local variable inside the closure you capture the value of m at that point in the loop.
you can also bind event another way, for sample
$("tr > td > input[type=checkbox]").function(e){
alert(event.target.id);
//OR
alert(this.id);
});
if you can add any class attribute in element
Then this is safe
$("tr > td > input[type=checkbox].switch").function(){
alert(event.target.id);
});
There is so many ways to do this. Here's one:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Populate Form
for (var m = 1; m <= 7; m++)
{
$('#content').append('<tr>' +
'<td>' + m + '</td>' +
'<td><input type="checkbox" class="clickMe" id="switch'+m+'"><label class="switch" for="switch'+m+'">Button ' + m + '</label></td>' +
'</tr>');
}
// Handle Click
$('.clickMe').click(function()
{
alert('You clicked on : ' + $(this).attr('id')); // alerts "switchN" e.g. switch1
// or //
alert('You clicked on : ' + $(this).attr('id').replace('switch', '')); // // alerts "N" e.g. 1
});
});
</script>
<table id="content"></table>
Here's a bit of a refactor (minus the button() plugin):
var $content = $('#content');
for (var m = 1; m < 7; m++) {
$content.append(
'<tr>' +
'<td>' + m + '</td>' +
'<td>' +
'<input type="checkbox" id="switch' + m + '">' +
'<label class="switch" data-num=' + m + ' for="switch' + m +'">Button ' + m + '</label>' +
'</td>' +
'</tr>'
);
}
$('label.switch').click(function(e) {
e.preventDefault();
alert($(this).data('num'));
});
JSFIDDLE
I am facing an issue with my jquery. I have used jQuery to add controls to table, along with a remove button to remove that particular row in table. here is my code on how i am creating controls in table.
HTML
<table id="controls" cellpadding="10" cellspacing="10">
</table>
<input id="btnAdd" type="button" value="Add" />
my jquery code looks like this
jquery
$(document).ready(function() {
$("#btnAdd").click(function() {
var field = $("#field").val();
var year = new Date().getFullYear()
var DDL_fromProfession = "<select name='ParametersFromProf' id='DDL_FromProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_fromProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_fromProfession += "</select>";
var DDL_ToProfession = "<select name='ParametersToProf' id='DDL_ToProYear'>";
for (var i = 1950; i <= year; i++) {
DDL_ToProfession += "<option text='" + i + "' value='" + i + "'>" + i + "</option>";
}
DDL_ToProfession += "</select>";
var newRow1 = "<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
var input = "<input name='parameters' id='field' type='text' />";
var input1 = "<input name='parametersCompany' id='field' type='text'/>"
//var inputCurrent="<input name='Current' id='Currfield' type='hidden'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " + input1 + "</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
to remove last row i am using.
jquery
$(document).ready(function() {
$("#controls").delegate("#btn_rmv", "click", function() {
$(this).closest("tr").remove();
return false;
});
});
clicking on remove button refresh the page and remove all the rows that i have added instead of last one.
NOTE: What i ahve digged out is .delegate is server side and it refresh the page. i am unable to remove last row with $("#btn_rmv").click(function() on my page
Please point me to right direction.
Thanks in advance
The code in question does not work as k is not defined, as used in the line
value='" + k + "'
If this error is corrected then the next problem is that you are creating multiple elements with the same id, as seen here
newRow1 += "<br/><button id='btn_rmv'>Remove</button>";
which in invalid HTML and will cause problems for jQuery in finding the element with the unique id.
By changing k for 0 and changing the id to a class, the remove code will only remove the current row with the button on. I assume that you really want to remove that row and also the preceding 2 rows.
$('#controls').delegate('.btn_rmv', 'click', function() {
var index = $(this).closest('tr').index() + 1 // as nth-child is 1-based indexing
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove(); // remove 3 rows
return false
});
See demo
Please note that since jQuery 1.7, .delegate() is superseded by .on() so the updated function is:
$('#controls').on('click', '.btn_rmv', function() {
var index = $(this).closest('tr').index() + 1
$('#controls tr:nth-child(n+' + (index - 2) + '):nth-child(-n+' + index + ')').remove();
return false
});
I had a similar experience: I was using Google Chrome and it would refresh the page everytime I called a function. You will have to return false. My problem was when I called a function from an element using "onclick". When I called the function from onclick I had to include the "return false;":
onclick="return false; functionName()"
Try this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
return false;
});
});
Or this and see if it works:
$(document).ready(function() {
$("#btnAdd").click(function() {
/* YOUR CODE */
});
return false;
});
Sorry my Javascript is not very good :(
You can do it in this way..
var RowCount = 0;
$(document).ready(function() {
$("#btnAdd").click(function() {
RowCount = RowCount + 1;
var newRow1 = "<tr id='tr" + RowCount + "'><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+ DDL_fromProfession + " to " + DDL_ToProfession + "</td></tr>"
+ "<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+ "<input type='checkbox' name='chkbx_CurrPro' value='" + k + "'>I currently work here</input>";
newRow1 += "<br/><button id='btn_rmv' onclick='RemoveRow(" + RowCount + ")'>Remove</button>";
});
});
function RemoveRow(RowID) {
$('#RemoveRow' + RowID).remove();
}
It looks like you are hooking up the remove click handler on $(document).ready.
On document.ready, the remove buttons do not yet exist (since they are generated dynamically when clicking 'Add', after the document.ready code has run). That's why $("#btn_rmv").click(function()... is not working.
So, after dynamically inserting a remove button in the $("#btnAdd").click event, you explicitly have to add a click handler to it.
EDIT:
If you generate your remove buttons with a unique id (eg. btn_rmv_1, btn_rmv_2, etc), you can add the following to your Add-handler (after appending the new button to the DOM):
$('#btn_rmv_1').click(removeButtonFunction);