I have one Table that is named CustomPickedTable, this Table have rows with attribute such as <td Data-question-id="5">Example</td> and some of the rows do not have any attribute at all. just <td>example</td>.
I want to do be able to sort em into different hiddenfields, these are my hiddenfields:
#Html.HiddenFor(model => model.SelectedCustomQuestions, new { #id = "SelectedQuestionsWithAttr" })
#Html.HiddenFor(model => model.SelectedQuestions, new { #id = "SelectedQuestionsWithNoAttr" })
the code that I have right now is that all rows with attribute "data-question-id" gets filled to SelectedQuestionsWithAttr that is my hiddenfield for rows with attributes.
But I want that my Jquery code also fills those rows with no attributes gets filled to my SelectedQuestiosnWithNoAttr hiddenfield.
This is the code for Just filling SelectedQuestionsWithAttr hiddenfield:
var selectedQuestionsWithAttr = $("#SelectedQuestionsWithAttr");
var currentIds = new Array();
$("#CustomPickedTable").find("td").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
selectedQuestionsWithAttr.val(currentIds.join(","));
$("form").submit();
}
Is there any solutions that can I add to my jquery code for this?
Thanks in Advance
You would need to add something onto the <td> tags to be able to identify them:
<td id="noAttr#(Model.SelectedQuestions.IndexOf(variable))">
Then the jQuery would be:
var $qWithAttr = $("#SelectedQuestionsWithAttr");
var $qWithoutAttr = $("#SelectedQuestionsWithNoAttr");
var currentIds = new Array();
var missingIds = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
currentIds.push($(this).attr("data-question-id"));
});
$("#CustomPickedTable td:not([data-question-id])").each(function () {
missingIds.push($(this).attr("id"));
});
$qWithAttr.val(currentIds.join(","));
$qWithoutAttr.val(missingIds.join(","));
$("form").submit();
Related
I am working on a project where I am finding difficulty in adding datetimepicker to dynamically added table rows. I have added datetimepicker to static table rows and it is working fine for them but not working for dynamically added table rows.
The tutorial I am following for datetimepicker
https://eonasdan.github.io/bootstrap-datetimepicker/
My Code I tried: I am cloning hidden rows.
Row Clone function:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
HTML of hidden td:
<td>
<div style="position: relative">
<input class = "form-control" type= "text" name = "datepicker" id= "datetime">
</div>
</td>
Messy but just init datetimepisker each time after you add a row...
$('#datetimepicker1').datetimepicker();
$('#datetimepicker2').datetimepicker();
etc
I was able to initialize the datetimepicker once the element was completely generated into the dom. working codepen
function addTableRow() {
var tbodyElement = document.getElementById("tbody");
var trElement = document.createElement("tr");
trElement.id = "generatedTr";
for (var x=0; x<3; x++) {
var tdElement = document.createElement("td");
var textNode = document.createTextNode("Generated td: " + x);
tdElement.appendChild(textNode);
trElement.appendChild(tdElement);
}
var finalTdElement = document.createElement("td");
var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.id = "generatedInput";
finalTdElement.appendChild(inputElement);
trElement.appendChild(finalTdElement);
tbodyElement.appendChild(trElement);
$('#generatedInput').datetimepicker();
}
If you have multiple elements that are being generated that needs the datetime picker, then I would suggest creating a class on all of them, then simply instantiate the plugin against that class like so.
$('.dateTimePickers').datetimepicker();
I would suggest don't initialize the datetimepicker every time after each element. better use following code. It will work like a charm.
I have been doing lot of research for this. Thus, Recommending to use Following code.
$('body').on('focus',".datetimepicker", function(){
$(this).datetimepicker();
});
I want to store the multiple id to hidden field.
So value able to bind to controller.
<form:hidden id="ids" path="ids" value="${ids }"/>
When click button delete will call jquery to delete row.
var deleteIds = [];
$("#deleteRow").on('click', function() {
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
$('#ids').val(deleteIds);
});
My question is
How to set the value into ids?
Thank You.
The tag from doesn't have the attribute value. You can check the attributes for the form tag here.
However, you can use jQuery to modify custom attributes. Here's a working fiddle:
var deleteIds = [];
deleteIds = ["1","2","3","4"];
$('#ids').attr("value",deleteIds);
alert($('#ids').attr("value"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ids" path="ids" value="${ids }"/>
By creating multiple <form:hidden/>, you can get what you want. I assume you when you click #deleteRow, table rows is deleted and you submit form of these ids to server, so we can make it by follow.
Cause I even don't know your html structure, so I've just tried to modify your script, may help you;)
var deleteIds = [];
$("#deleteRow").on('click', function() {
$('#ids').remove();
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
for (var i = 0; i < deleteIds.length; i++) {
// formId should be replaced to your form id
$('#formId').append('<form:hidden id="ids" path="ids" value="' + deleteIds[i] +'"/>');
}
// $('#formId').submit(); comment this line, cause there is another button to submit form.
});
I able to set the multiples value to hidden field. Answer as below.
<form:hidden id="ids" path="ids" value="${ids }"/>
$("#deleteRow").on('click', function() {
var deleteIds = [];
$('.case:checkbox:checked').each(function(i){
if($('#ids').val() != ''){
deleteIds[i] = $('#ids').val() + "," + $(this).val();
}else{
deleteIds[i] = $(this).val();
}
});
$('#ids').attr("value",deleteIds);
});
The each(function(i)) will loop all the checkbox and store in array[], after that assign the array to hidden field.
Here is my jQuery, I have it working properly but once my row is added the user input in the inputs are still there and not cleared. How do I fix this?
// Removing menu rows
$('.menu-items').on('click', '.delete', function(){
$(this).closest('.menu-row').remove();
});
// HTML
var MENU_ROW_TEMPLATE = '<div class="menu-row"><span class="item-description">$description</span><div class="control-items"><span class="item-price">$price</span><span class="delete">X</span></div></div>'
// Adding menu rows
$('.menu-category').on('click', 'button', function(){
var $row = $(this).closest('.add-item');
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
var newRowHtml = MENU_ROW_TEMPLATE.replace('$description', name).replace('$price', price);
var $newRow = $(newRowHtml);
var $lastMenuRow = $row.closest('.menu-category').find('.menu-row').last();
$newRow.insertAfter($lastMenuRow);
});
Sorry for my poor explaining skills.
Clear the name and price after you get the values...
...
var name = $row.find('input').first().val();
var price = $row.find('input').last().val();
$row.find('input').first().val('');
$row.find('input').last().val('');
...
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);
}
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.