Get Id of table row if it is checked? - javascript

I have a datatable containing a list of Cars. each row in the html contains a Car ID. I have added checkbox column to the first cell in my datatable - if it is checked the row is highligted to indicate to the user they have selected that row. What I waht to do is get all the IDs of all the cars a user has selected on clicking a button on the page. (also there are other columns in the table row where I have checkboxes (i.e - a Manual column or an Automatic column which will somtime be checked - like in column 5 ot 6 in the table)
so this is part of the cshtml for my page..
#foreach (var car in Model.Cars)
{
<tr carId="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
//more stuff set in other tds in table
Then this is the JS I have for the page so far.
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
carsListTable.find("tr").each(function (index, para) {
$('tr').find('td:input:checked:first').each(function () {
var car= new Object();
alert($(this).parent().parent().attr("carId"));
car.ID = $(this).parent().parent().attr("carId");
cars.push(car);
});
});
var jsonString = $.toJSON(cars);
I want to then return the json string to my controller (I do this by passing the value into a hidden field on my model and then deserialize - but at the minute I am getting it as empty. My problem is getting the best way to get the id from the row if it is checked?

You can use the selectors :checkbox:checked and use the jQuery.map to convert the array. The jQuery.closest() method will give the closest ancestor matching the given selector.
var cars = carsListTable.find('.table-data :checkbox:checked').map(function(i, v){
return {
ID : $(v).closest('tr').attr('carId')
}
});
Demo Fiddle
Note: The id of elements should be unique in a document so the id of the checkbox should be removed or has to be suffixed or prefixed by a dynamic value like the car id.

First, you should use class instead id for elements that will be present more than once. I suggest change #SelectIndividual for .SelectIndividual on the checkbox input). Another thing you should change is the carId attribute, because is not semantic valid. You should use custom data attributes instead. This is how your code should look like:
HTML
#foreach (var car in Model.Cars)
{
<tr data-carID="#Html.DisplayFor(modelItem => car.CarID)">
<td class="table-data">
<input id="SelectIndividual" name="Select" type="checkbox" />
</td>
Jquery
$('#GetSelectedCars').click(function (event) {
var cars= new Array();
$('SelectIndividual:checked').each(function () {
var car= new Object();
car.ID = $(this).parent().parent().data('carID');
cars.push(car);
});
});
//keep doing things

I would suggest to use the data-* attributes that are valid HTML5 as well as the jQuery.data() methods for the id of the car.

Can you assign a class to all checkboxes in first column and then try this
$('.cbClass:checked').each(function () {
tr = $(this).closest('tr');
// use the row
})

Related

Get X and Y position after searching an element in a HTML table

I'm having troubles thinking a solution to this problem.
I have this table and a JSON like this one:
{:id=>"e-123",
:subject_initials=>"IN",
:grade=>"12"}
I need to search on the table the id of the person (which in this case is "e-123") and search on the first row the initials of the subject and put the grade on the X and Y position.
The result of the example above should be something like this
Any idea how to do this?
Need to search through the heading inputs to get a column index and search through the user id inputs to get a row index then use eq() method to isolate the one you need to update
var $subjectInput = $('tr').first().find('input').filter(function() {
return this.value === data.subject_initials
});
var $idInput = $('tr').find('td:eq(1) input').filter(function() {
return this.value.toLowerCase() === data.id
});
var colIdx = $subjectInput.parent('td').index();
var rowIdx = $idInput.closest('tr').index();
$('tr').eq(rowIdx).find('td').eq(colIdx).find('input').val(data.grade)
Adding some additional classes on these 2 types of inputs would help make the selectors for finding them easier
If the rows are generated dynamically adding an ID to the row and course name class to the data entry inputs you could simplify the whole thing immensely
<tr id="e-123">
.....
<input class="form-control course_IN">
JS
$('#' + data.id).find('input.course_' + data.subject_initials).val(data.grade)
DEMO

Replace Key name array inputs jquery

I've got a strange question. We have buttons that have data attributes with an id in it. [v1, v2 and v3].
<table id="table-1" data-car-id="v1">
<tr><td>Header1</td></tr>
<tr><td>Content1 <input type="text" name="car[v1][marked][12]" /></td></tr>
<tr><td>Footer</td></tr>
</table>
<button id="copy-2" data-car-id="v2">Copy Table</button>
<table id="table-2">
</table>
<button id="copy-3" data-car-id="v3">Copy Table</button>
<table id="table-3">
</table>
A little piece of Javascript copies the body of the above table to closest next one. (That works).
$("button[id^='copy']").click(function() {
var $carId = $(this).attr('data-car-id');
alert($carId);
var $prevTable = $(this).prev("table[id^='table-']").prop('innerHTML');
var $nextTable = $(this).next("table").html($prevTable);
});
But now the tricky part, the input name of all inputs in that tbody should be replace. While the market should remain unchanged
car[v1][marked][12] => car[v2][marked][12]
How can I do that? Make it yourself easy and use the JSFiddle I created: https://jsfiddle.net/ra35z8ff/
After copying the HTML over to the next table element, select all the children input elements and iterate over them. Use the .replace() method to replace the previous table element's data-car-id attribute with the current button element's data-car-id attribute.
Updated Example
$("button[id^='copy']").on('click', function () {
var id = $(this).attr('data-car-id'),
previousId = $(this).prev('button').attr('data-car-id');
html = $(this).prev("table[id^='table-']").prop('innerHTML');
$(this).next("table").html(html).find('input').each(function () {
this.name = this.name.replace(previousId, id);
});
});

Dynamically add rows into a table using data from another table-jQuery

I have two table on my page like the picture shown here.
What I want to do is:
select rows in the Source Table
read the data in ID field, Name field from the Source Table, and also the value of radio button.
Form these data as rows of Target Table and append these rows into Target Table.
Now Im using two arrays to store the ID and Name that read from Source Table, but im a bit confused about how to form a row for the Target Table.
$('#btnLinkCase').click(function (event) {
var caseID = $('#caseID').text();
var linkedIDArr = []; //array list for selected id
var linkedNameArr = []; //array list for selected name
$('#linkCaseTable tbody tr td:nth-child(2)').each(function (index, el) { //store each paire of <tr> into array
linkedIDArr.push(el);
});
$('#linkCaseTable tbody tr td:last-child').each(function (index, el) { //store each paire of <tr> into array
linkedNameArr.push(el);
});
$.each(linkedCaseIDArr, function (index, val) {
//whats next?
});
});
Please see all source code here
Any ideas of doing this? Thanks in advance
Edit:
If multiple rows are selected they will use the same value from the radio button. eg: two rows are selected and "Type 1" is checked. In target table, their relationship all are "Type 1". I hope I have explained myself..
Try:
$('button').click(function (event) {
$("#sourceTable tr:gt(0)").each(function(){
var th = $(this);
console.log("dfg")
if($(th).find("input[name='link-cbx']").is(":checked")){ //assuming ids are unique remove condition if you do notwant so
var id = $(th).find("td:eq(1)").text();
var name = $(th).find("td:eq(7)").text();
var type = "Type "+$("input[name='linkType']:checked").val();
if($("#targetTable:contains('"+id+"')").length < 1){
$("#targetTable").append("<tr><td>"+id+"</td><td>"+name+"</td><td>"+type+"</td></tr>");
}
}
});
});
Updated fiddle here.

Jquery conditional statement

My html
<tr id="uniqueRowId">
<td>
<input class="myChk" type="checkbox" />
</td>
<td class="from">
<textarea class="fromInput" ...></textarea>
</td>
<td class="to">
<textarea ...></textarea>
</td>
</tr>
I have a table where each row is similar to the above with only one exception: not all rows will have textreas. I need to grab all rows that have textareas AND checkbox is not "checked".
Then I need to leaf through them and do some stuff.
I tried something like:
var editableRows = $("td.from .fromInput");
for (s in editableRows)
{
$s.val("test value");
}
but it didn't work.
1) how do I grab ONLY the rows that have checkboxes off AND have fromInput textareas?
2) how do I leaf through them and access the val() of both textareas?
I am sure this could be optimized, but I think it will work.
$("tr:not(:has(:checked))").each(function(i, tr) {
var from = $(tr).find("td.from textarea").val();
var to = $(tr).find("td.to textarea").val();
//now do something with "from" and "to"
});
See it working on jsFiddle: http://jsfiddle.net/RRPqb/
You can use this to select the rows:
$('tr', '#yourTable').has('input:checkbox:not(:checked)').has('textarea')
Live demo: http://jsfiddle.net/simevidas/Zk5EH/1/
As you can see in the demo, only the row that has a TEXTAREA element and a unchecked checkbox will be selected.
However, I recommend you to set classes to your rows: the TR elements that contain TEXTAREA elements should have a specific class set - like "directions". Then you could select those rows easily like so:
$('tr.directions', '#yourTable').each(function() {
if ( $(this).find('input:checkbox')[0].checked ) return;
// do your thing
});
$("tr:not(:has(:checked)):has(input.fromInput)")
Should be what you need. All the rows that don't have anything checked but that do have an input with the class 'fromInput'
If you want to loop through them to get the value of any textarea just extend your selector:
$("tr:not(:has(:checked)):has(textarea.fromInput) textarea")
Or as above if you want to be able to distinguish them:
$("tr:not(:has(:checked)):has(textarea.fromInput)")
.each(function() {
var from = $(this).find("td.from textarea").val();
var to = $(this).find("td.to textarea").val();
})
I don't know how much performance is a concern here, but if it is, then rather then writing a selector to find rows that contain a textarea you may find it helps to add a class to the row itself.
<tr class="hasTextarea">
Then you could alter your JQuery as so:
$("tr.hasTextarea:not(:has(:checked))")

Javascript - filling textboxes with checkbox value

In my web application, I've set of checkboxes which on check populate a textbox above them.(If more than one checkbox is selected, then their values appear in the textbox separated by commas).
These set of checkboxes appear as rows in my HTML table.
Here's my HTML code.
<input type="text" id="newContactComment<%=rCount %>" name="newContactComment" size="45">
<input type="checkbox" id="commentText<%=rCount %>" name="commentText" value="<%=c.getComment_text() %>"
onclick="javascript:updateTextArea(<%=rCount%>);">
And the corresponding JS function is as follows:
function updateTextArea(rCount) {
var allVals = new Array();
$("#contactInfo input['commentText' + rCount]:checked").each(function() {
(allVals).push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
}
The rCount variable in the above function is the row # of my table.
Using this above, I'm not getting the expected behaviour..
For ex. If for row 1 of my table, I check chkbox 1 and 2, it correctly gets populated with values of those checkboxes. Now, for 2 of my table, I check only chkbox 3, it gets populated with the values 1,2 and 3 and not only 3 as I expect it to.
Any help will be greatly appreciated.
It would be better to use jQuery to set an event handler rather than setting it inline.
You want to use the onchange event not the onclick event.
If you add class names of checkboxes (or whatever you want) to the checkboxes the following will work:
$("input.checkboxes").change(function(){ //when checkbox is ticked or unticked
var par = $(this).closest("tr")[0];
var parID = par.id;
var patt1=/([0-9]+)$/g;
var rCount = parID.match(patt1); //Gets number off end of id
var allVals = new Array();
//Get all checkboxes in current row that are checked
$(par).find("td input.checkboxes:checked").each(function() {
allVals.push($(this).val());
});
$("#newContactComment" + rCount).val(allVals);
allVals = null; //empty array as not needed
});
I believe this or something along these lines will do what you want
You're trying to use the rCount variable from within the quoted string. Try this instead:
$("#contactInfo input['commentText" + rCount + "']:checked")

Categories

Resources