I have a slickgrid in which some rows are hidden by a filter (DataView).
When I now call the getSelectedRows method of the grid I get the indices of the visibly selected rows. But I need the actual data of the selected rows.
You must do something like this:
var selectedData = [],
selectedIndexes;
selectedIndexes = _grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(_grid.getData()[value]);
});
Right now the selectedData variable contains data for selected rows.
You have a mistake. It needs to be "getDataItem" and not "getData".
var selectedData = [],enter code here`selectedIndexes;
selectedIndexes = _grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(_grid.getDataItem(value));
});
hObjMarcado = ( grid.getSelectedRows());
for( var a_id in hObjMarcado ) {
vres.push( dataview.getItem( hObjMarcado[a_id] ));
//la opcion getItem obtiene el elemento especifico,
//aun con filtro.
}
return vres;
You can also use this line in the .each loop to pull the data from the dataView instead of using getData() from the grid object, since that seems to be inconsistent depending on the fork:
var selectedData = [],
selectedIndexes;
selectedIndexes = _grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(_dataView.getItemById(value));
});
If you access grid from other control like . click button
var selectRow = gridInstance.getSelectedRows();
alert(gridInstance.getDataItem(selectRow).columnName)
Related
im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.
I have large form mainly drop down lists and checkboxes. Checkboxes are created dynamically so i don't know their id's before they are created. I use drop down onChange event to do create them on the fly.
How can i loop trough the form and get all the checkboxes that are checked, that is their id and their value? I need to do this only for check boxes that are checked. All checkboxes share the same name, that is: categoriesfilters[]. Currently i have on click event on the checkbox which invoke the javascript function.
Here is the code:
function update_number_of_adds_found(field_dropdown,selected_value) {
selected_value="";
var addtypeid = $("#addtypeid").val();
// trying to store the values of the checkboxes
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
alert(value);
}
);
var selected_value = {
addtypeid: addtypeid,
// need to add the ids and the values here as well
};
var url = "<?php echo site_url('search/findNumberOfAdds'); ?>";
$.post(url, selected_value, function(r){
if(r) {
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(r.result);
} else {
// alert(selected_value);
}
}, 'json')
}
Regards, John
Try this :
var categories = [];
$("input[name='categoriesfilters[]']:checked").each(
function() {
var id = $(this).attr("id");
var value = $(this).val();
categories[categories.length] = {id : value};
}
);
console.log(categories);
$.post(url, categories, function(r){
...
Try this :
$('form').submit(function(){
$(this).find("input[type=checkbox]:checked").each(
function() {
var id = $(this).attr('id');
var value = $(this).val(); // or maybe attr('value');
// the data is stored, do whatever you want with it.
}
);
});
I guess you want to check that on form submit.
var arr = [];
$('input[name^="categoriesfilters"]:checked').each(function() {
var obj = {
id: $(this).attr('id');
value: $(this).val();
};
arr.push(obj);
});
console.log(arr); // show us the array of objects
Would you like to use Jquery?
Add a class to each of the checkbox i.e "class_chk";
$(function(){
$('.class_chk').each(function(){
if($(this).is(':checked')){
var id = $(this).attr('id');
var val = $(this).val();
alert("id = "+id+"---- value ="+val);
}
});
});
The above way you can get all the check box id and value those are checked.
Thanks..
I have an asp.net page - I am using jQuery datatables on it.
Part of the code is below:
<% foreach (SubmissionSearchResult result in SearchResults)
{%>
<tr data-name='<%=result.ID %>'>
So each time a row is drew on screen I am adding a data-name of result ID to it. What I want then is on clicking the row retrieve this ID.
I had something like the below to start :
$('#searchResultsTbl').on("click", "tbody tr", function () {
var nTds = $('td', this);
var id = $(nTds[0]).text().trim();
This worked when the id was in the first td in the row but now the columns can be dynammic and it may not be in the first column. So I wanted to add the id to each row and then get it from the row so I added it as a data-name but not sure on how to get the value back from it?
$('#searchResultsTbl').on("click", "tbody tr", function () {
var id = $(this).data('name');
});
try this
$('#searchResultsTbl tr:gt(0)').click(function () {
var this_row = $(this);
var data_name = this_row.attr('data-name');//row attribute
var first_td = $.trim(this_row.find('td:eq(0)').html());
var second_td = $.trim(this_row.find('td:eq(1)').html());
var third_td = $.trim(this_row.find('td:eq(2)').html());//and so on
});
add the javascript function on click event of row
like
<tr data-name='<%=result.ID %>' onclick='showid("<%=result.ID %>")'>
Now in javascript define this showid function
function showid(rowvalue)
{
alert(rowvalue);
}
this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});
I want to extract data from an html table like
<table>
<tr>
<th> Header1 </th>
<th> Header2 </th>
<th> Header3 </th>
</tr>
<tr>
<td> Value 1,1 </td>
<td> Value 2,1 </td>
<td> Value 3,1 </td>
</tr>
... rows ...
</table>
and get arrays:
an array for the headers
a 2d array for the column values (or an array for each column)
How can I do this using jQuery?
I don't care to serialize it, or put it into a JSON object because I want to use it to render a chart.
related General design question:
at the moment I have something like
1. ajax query returns html table
2. use jQuery to get values from html table
3. render chart
does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?
demo updated http://jsfiddle.net/ish1301/cnsnk/
var header = Array();
$("table tr th").each(function(i, v){
header[i] = $(this).text();
})
alert(header);
var data = Array();
$("table tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
});
})
alert(data);
Something like this?
$(function() {
var headers = $("span",$("#tblVersions")).map(function() {
return this.innerHTML;
}).get();
var rows = $("tbody tr",$("#tblVersions")).map(function() {
return [$("td:eq(0) input:checkbox:checked",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
alert(rows);
});
yet another way of doing it
var headers = jQuery('th').map(function(i,e) { return e.innerHTML;}).get();
var datas = []
jQuery.each(jQuery('tr:gt(0)'), function(i,e ) {
datas.push(jQuery('td', e).map(function(i,e) {
return e.innerHTML;
}).get()
);
});
Something along the lines of:
var thArray = new Array();
var contentArray = new Array();
$('th').each(function(index) {
thArray[index] = $(this).html();
})
$('tr').each(function(indexParent) {
contentArray['row'+indexParent] = new Array();
$(this).children().each(function(indexChild) {
contentArray['row'+indexParent]['col'+indexChild] = $(this).html();
});
});
This gives you two arrays, thArray which is an array of your headings and contentArray which is a 2d array containing rows and columns: contentArray['row1']['col0'] returns " Value 1,1"
Actually, contentArray contains the th's as well... referenced 'row0'
does it make more sense to throw a JSON object back from the ajax query and then render a table and a chart from there?
Yes, absolutely. Return JSON in response to your AJAX request, then you can render the table using something like jQuery Templates and use the same underlying data to generate your chart as well.
Here's a modification of Jerome Wagner's answer that uses recursive maps instead of a map inside an 'each':
http://jsbin.com/oveva3/383/edit
var headers = $("th",$("#meme")).map(function() {
return this.innerHTML;
}).get();
var rows = $("tbody tr",$("#meme")).map(function() {
return [$("td",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
I'm tinkering with the same thing over here, but I prefer iterating through all tables and writing the header and body arrays into properties of each table, so here's my modification to the original answer:
$(function() {
$("table").each(function(){
var $table = $(this),
$headerCells = $("thead th", $(this)),
$rows = $("tbody tr", $(this));
var headers = [],
rows = [];
$headerCells.each(function(k,v) {
headers[headers.length] = $(this).text();
$table.prop("headAry", headers);
});
$rows.each(function(row,v) {
$(this).find("td").each(function(cell,v) {
if (typeof rows[cell] === 'undefined') rows[cell] = [];
rows[cell][row] = $(this).text();
$table.prop("bodAry", rows);
});
});
console.log($(this).prop('headAry'));
console.log($(this).prop('bodAry'));
});
});
JSbin
Use this line of code:
var arrays = [];
$('table').eq(0).find('tr').each((r,row) => arrays.push($(row).find('td,th').map((c,cell) => $(cell).text()).toArray()))
I would think it would make more sense to get a json array back from the ajax call and generate your table/chart from that. With jquery templates this isn't hard at all.