JQuery add class to row based on a value - javascript

I am reading a data from SQL Server database and displaying it in the form of a table. However, I need help on how to add a styling to a row in a table based on a value of one of the attributes using jquery
The column has a class like so
<td>
<span class="funding-eligible">#Html.DisplayFor(modelItem => item.FundingEligibility)</span>
</td>
In the javascript file I have this
$(document).ready(function () {
if ($(".funding-eligible").text() == 1) {
$(".funding-eligible").addClass("eligible")
}
});

Loop through funding-eligible class .each() then use closest() to get the parent row
$(document).ready(function () {
$(".funding-eligible").each(function(){ // .each to loop through elements
if(+$(this).text().trim() === 1){ // .trim() to avoid white-spaces , + here to covert the string to number
$(this).closest('tr').addClass("eligible"); // .closest() to get the closest row
}
})
});
You can also use .filter()
$(document).ready(function () {
$(".funding-eligible").filter(function(){ // .filter to filter elements by condition returned
return +$(this).text().trim() === 1; // .trim() to avoid white-spaces , + here to covert the string to number
}).closest('tr').addClass("eligible"); // .closest() to get the closest row
});
But.. Why you don't use a condition to add a class to row directly in your html before appending?? something like<tr class="<?php echo ($eligible == 1) ? 'eligible' : '' ?>">

Related

How can I use one event handler for multiple radio buttons?

I want mutliple radio buttons (number unknown, because they get created dynamcially) to have the same onClick or onChange event, whichever fits the best. I found examples for jQuery but not pure Javascript. Should i just loop trought all radio buttons on the form?
They get created in php like so:
//DB Connection already established
$sql = "SELECT * FROM users";
$results = $dbConnection->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch-assoc()){
echo "<li><input type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
}
}
else
{
echo "<p>No users found</p>";
}
How can i do that loop? Or is there any more common way of doing that?
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Or Should i just add onclick=myfunction(this) into the php file?
I want multiple radio buttons (number unknown, because they get created dynamically) to have the same onClick or onChange event.
If one of them get's clicked i want their value as a parameter for the event, in only one function.
Let's assume that your PHP has rendered the list items and you have a common function called myFunction() which you want to use to log it's parameter to your console:
function myFunction(val){
console.log("The value is " + val);
};
Now if I understand you correctly, you want to run the above function whenever one of the rendered radio buttons are clicked and to pass the value of the value attribute of the radio button that was clicked as a parameter for the above function.
Firstly, you need to assigned all the rendered radio button in your list to a variable:
var x = document.querySelectorAll("li input");
Secondly, since x is a collection of objects (here, all the radio buttons rendered), you will now have to map through each item on x using forEach and assign a click listener on each radio button which runs the ClickItem()function passing it the item's defaultValue as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.defaultValue;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/56/
However, if by value, you mean the content after the input tag but still inside the respective li tag, then you just need to make slight changes to the above code like this:
Firstly, to prevent the selector from querying li elements from other parts of the page, you need to wrapped your list items with a div or a ul having a unique ID like this:
<ul id="someList">
//create your list items here
</ul>
Secondly, you need to assigned all the rendered list items to a variable:
var x = document.querySelectorAll("#someList li");
Thirdly, similarly to what we did above, since x is a collection of objects (here, all the list items rendered), you will now have to map through each item on x using forEach and assign a click listener on each list item which runs the ClickItem()function passing it the item's innerText as a parameter val like this:
x.forEach(function(radio) {
radio.addEventListener('click', function() {
var val = this.innerText;
myFunction(val);
});
});
jsFiddle: http://jsfiddle.net/AndrewL64/2y6eqhb0/58/
Actually the JQuery make it easier, but you can do the same with pure JS.
the real concept is to capture the event bubbling, try this:
fatherElement => element that is not dynamic
fatherElement.addEventListener("click", function(event){
if(event.target.type == 'radio'){
//do something
}
});
Use this echo line instead yours:
echo "<li><input onchange='yourOnChange(event)' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>";
I add onchange='yourOnChange(event)' there. And of course remember to add proper js function e.g function yourOnChange(e) { console.log(e); } to your web page.
Or Should i just add onclick=myfunction(this) into the php file?
Yes, you can do that. In that case code will be;
<li><input onclick='myclick('". $row['E-Mail'] ."')' type=radio name=all_users[] value='". $row['E-Mail'] . "'/>" . $row['Name'] . " " . $row['Lastname'] . "</li>"
Now in JS code myclick(email) function can handle anything with email argument.
Pure JS solution:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'radio') {
if(inputs[i].checked)
{
//if radio button is checked
myClick(inputs[i].id, 'checked') //you can get anything apart from id also
}
else
{
//if radio button is not checked
myClick(inputs[i].id, 'unchecked') //you can get anything apart from id also
}
}
}
myClick(id, stat)
{
//YAY!! I have got the id
}
You can do a for of loop if you have querySelectorAll.
Here is an example:
const radios = document.querySelectorAll('input[type=radio]');
for (const element of radios ) {element.addEventListener('click', function(event) {
console.log(event.currentTarget)
})
}
Using pure JS you can select your radio buttons and add event listeners like so:
const radios = document.querySelectorAll('input[type=radio]');
radios.forEach(radio => radio.addEventListener('change', e => {
// radio is your radio button element
});
Same with jQuery:
$('input[type=radio]').change(() => {
//your code goes here
});

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

Find exact value in cell of a table and add class to row

I am trying to use jquery to find a exact value in a cell in a table then add a class to that row I currently have this bit of code.
$("tr").find(".closeID:contains(2)").parent('tr').addClass('selected');
Which does work but its doing contains so if any cell with the class closeID has the value in will add the class but I want it to be exact so that if I look for the number 1 it won't add the class to 1,10,11,12,13 and so on.
This is one of my rows in my table the data is pulled in with php.
<tr>
<td>'. $i++ .'</td>
<td>'.dateTime($data['submit_date']).'</td>
<td>'.dateTime($data['event_date']).'</td>
<td>'.$data['project_code'].'</td>
<td>'.$data['project_name'].'</td>
<td>'.$data['event'].'</td>
<td>'.$data['happened'].'</td>
<td>'.$data['about'].'</td>
<td>'.$data['reporter'].'</td>
<td>'.$data['org'].'</td>
<td>'.$data['trackside'].'</td>
<td>'.$data['location'].'</td>
<td>'.$data['number'].'</td>
<td>'.$data['breach_rule'].'</td>
<td>'.$data['life_rule'].'</td>
<td>'.$data['require_feed'].'</td>
<td>'.$data['email'].'</td>
<td>'.get_region_id($data['region']).'</td>
<td>'.$data['closed_out'].'</td>
<td>'.$data['rssb_num'].'</td>
<td style="display:none;" class="closeID">'.$data['id'].'</td>
<td style="display:none;">'.$data['file_upload'].'</td>
</tr>
If you can help that would be great.
Thanks for your time.
There is no way to do an exact match test, so you will need to loop over the collection and checking the value.
$(".closeID").filter( function () {
return $.trim( $(this).text() ) == "1";
}).closest("tr").addClass("selected");
over option, use a data attribute instead of using text in a TD. This way you can just reference it with a simple selector.
<tr data-id="10">
and just use an attribute selector
$('tr[data-id="10"]').addClass("selected");
You could loop through each cell in your table and check the value. I'd recommend using plain javascript over jQuery for this (it'll run much quicker)
var table = document.getElementById('your-table-id');
var rows = table.getElementsByTagName('tr');
for (var row = 0; row < rows.length; row++) {
var cells = rows[row].getElementsByTagName('td');
for (var cell = 0; cells < cells.length; cell++) {
if (cell.innerHTML === 'the string your looking for'){
jQuery(rows[row])
.parent('tr')
.addClass('selected');
}
}
}
try
$(".closeID").filter(function(i,DOM){
return (/*condition here*/);
})
.closest('tr')
.addClass('selected')‌​;
The first part $(".closeID"), gets you the list off all the tags with the closeID css class. Then the filter function lets you choose which you want. Then the last part lets you make the modification you want.

How to construct the id of an element and perform actions on it in JQuery?

I have a button in my table row which is having an id btn_number_$i. On clicking the button I want to show the table row having id row_$i, which is initially hidden.
Here is my PHP code to create the two table rows:
echo "<tr><td>"."<button id= \"btn_number_$i\" class='btn info toggler' >Info <i class='icon-arrow-down'></i></button>"."</td></tr>";
echo "<tr id='row_$i' class='info_row'><td>Hello There!!</td></tr>";
And below is my jQuery code.
I am trying to construct the similarly named row id and perform .show on it. But I am not getting the desired result.
$(function () {
$('.info_row').hide(); // first I need to hide all the second rows.
$('.toggler').click(function () {
var currentId = $(this).attr('id');
console.log(currentId);
var lastChar = currentId.substr(currentId.length - 1); //Herein I am trying to extract the last character from btn_number_$i which is $i and then appending it with 'row_'
var rowId = 'row_' + lastChar;
console.log(rowId); // I am able to get the current value in console log.
$('#rowId').show(); // But even after all that i am not able to show the element.
});
});
Any help will be thankfully appreciated.
You are not using the variable rowId containing id you constructed but using rowId a string literal. The selector you have will be looking element with id = rowId
Change
$('#rowId').show();
To
$('#' + rowId).show();

Get Id of table row if it is checked?

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
})

Categories

Resources