Hide row of table depending on variable value - javascript

I'm pretty new at this so bear with me.
If I have variable "A" = 0, I want to hide the row (preferably collapse the row). The button will at 1 to variable "A" and the row will appear.
<body>
<tr id=rowA>
<td>Stat:</td>
<td><span id="Value">0</span></td>
<td><button type="button" id = add onclick="add(1)">+</button>
<button type="button" disabled id = minus onclick="add(-1)">-</button></td>
<td></td>
<td></td>
</tr>
//this button will add 1 to A which is shown
<button type="button" id = minus onclick="add(1)">-</button></td>
</body>
<script>
var A = 0;
var add = function(valuetoadd){
A += valuetoadd;
</script>
Ignore the value in each cell of the row, but I want to hide the row if A == 0 and if it is >=1 the row will show.

With pure javascript it will be:
if (A==0)
{
document.getElementById("rowA").style.display="none";
}
else
{
document.getElementById("rowA").style.display="";
}
with jQuery :
if (A==0)
{
$("#rowA").hide();
}
else
{
$("#rowA").show();
}
with jQuery you also can use fadeIn() and fadeOut() functions for smooth transition.

Related

On button click same row checkbox should be checked

I have placed a button and checkbox at end of each row of the table. I want now is that if I click button in row 1 then checkbox only in row 1 gets checked and so on. code is working fine if I go from 1st to last row turn by turn.
Problem occurs if I click directly on for eg. 2nd row. if I click in 2nd row then the checkbox in 1st row is selected.
I have tried matching the ids of button and checkbox control but that is not possible as the name in id will always be different.
cols += '<td><button type="button" class="btn btn-info btn-sm btn-block" onclick="req_ser()" id="check_btn' + limit + '" value="' + data + '">Request</button></td>';
cols +='<td><input type="checkbox" class="chec" id="check' + limit + '" value="' + data + '" disabled="disabled"></input></td>';
function req_ser() {
var sl_num = [];
var count = 0;
for (var bv = 0; bv <= limit; bv++) {
var stai;
var bvv = bv + 1;
var cls = document.getElementsByClassName("btn btn-info btn-sm btn-block");
var chs = document.getElementsByClassName("chec")
cls[bv].id = "check_btn" + (bv + 1);
chs[bv].id = "check" + (bv + 1);
alert(cls[bv].id);
alert(chs[bv].id);
//stai = $('#check' + bvv + '').on(':click');
//stai = $('#check' + bvv + '').is(':clicked');
//stai = $('#check' + bvv + '').data(':clicked', true);
$('#check' + bvv + '').prop('checked', true);
stai = $('#check' + bvv + '').is(':checked');
if (stai == true) {
sl_num.push({
"serial": document.getElementById("slnchk" + bvv + "").innerText,
});
break;
}
}
expected result is whichever row button I click only that row checkbox should be checked. Please guide regarding this.
You can do it with .closest() and .find() in jquery.
Example:
$('td .btn').on("click", function() {
$(this).closest('tr').find('.chec').prop("checked", true);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
<tr>
<td><button type="button" class="btn btn-info btn-sm btn-block">Request</button></td>
<td><input type="checkbox" class="chec" disabled="disabled"></td>
</tr>
</table>
It's not too difficult with just vanilla JS:
A click listener calls the checkit function.
Inside the function, all the code is wrapped in an if block so it only runs if the clicked element is one of the buttons (which, in this case, are identified by the checkBtn class).
The function automatically has access to the event that triggered it. We refer to this argument as event for ease of reading.
The event's target property gives us the button that was clicked.
From there, we get the closest ancestor element with the tagName TR, and we call it row.
Within this row, we get all the input elements, take the first one, and call it checkbox.
To this checkbox, we add the attribute "checked" (with an empty string as its value).
Note: The lines that are commented out would let the user toggle the "check" by clicking again.
document.addEventListener("click", checkit);
function checkit(event){
if(event.target.classList.contains("checkBtn")){
const row = event.target.closest("TR");
const checkbox = row.getElementsByTagName("INPUT")[0];
//if(checkbox.checked){ checkbox.removeAttribute("checked"); }
//else{
checkbox.setAttribute("checked", "");
//}
}
}
<table>
<tr>
<td><button class="checkBtn">Click me</button></td>
<td><input type="checkbox" value="one" /></td>
</tr>
<tr>
<td><button class="checkBtn">Click me</button></td>
<td><input type="checkbox" value="two" /></td>
</tr>
</table>
Alternatively (and if speed is not a concern), you can add a separate eventListener to each button as you create it. In this case, the if condition would be unnecessary.
This code could be shorter but the example is more explicit for the sake of clarity.

How to manipulate background color of a row and a table using Javascript

I have an application whereby when the user clicks on Add New Item button rows are added dynamically using Javascript and each input field in the row added dynamically has a unique id and this works fine.
When any number on the table on the left is clicked it is populated dynamically in the row on the left. When another number on the table on the right is clicked it populates on the single input on the right (after the plus icon).
When I hover over the 1st row the background color changes to green including the corresponding match on the table on the left which works fine.
Am trying to add a logic whereby
a.) if the user clicks on Add New Item button to add a new row (the row is added according to the format of the 1st row).
b.) After the user clicks on any td number on the 2 tables (right and left) and their values are populates in the rows dynamically (value on the left table populates in the row before + sign and value in the right table populates in the right table after + sign), when the user hovers over the values on the rows their background color should change immediately and conform to the values of the tables they were previously chosen from...
NB ~ Basically I want the behavior on the 1st row (after mouseover when inputs are filled from respective tables) to be simulated across proceeding rows that are added dynamically after the button is clicked.
JsFiddle link: Js Fiddle
~ Kindly assist on this quite challenging task..
Javascript code which is commented to show my steps in the task
//Add row input fields dynamically on button click
// Starting number of inputs
let count = 5;
// Wrapper
const wrapper = document.querySelector("#wrapper");
document.querySelector("#btn").addEventListener("click", () => {
const container = document.createElement("div");
for (let i = 0; i < 5; i++) {
// Increment the count to ensure that it is unique
count++;
// Create new `<input>` element
const input = document.createElement("input");
input.type = "text";
input.name = count;
input.size = "4";
input.id = `inp${count}`;
container.appendChild(input);
// Optional: add empty whitespace after each child
container.append(document.createTextNode(" "));
}
wrapper.appendChild(container);
});
//END creating rows dynamically
let currentInput = 1;
let bonusInput = 1;
//Left table on click event
$("#table1 td").on("click", function(event) {
//gets the number associated with the click
let num = $(this).text();
//Populate it in 1st row input fields (before plus sign)
$("#inp" + currentInput++).attr("value", num);
});
//Right table on click event
$("#table2").on("click", function(event) {
//gets the number associated with the click
let bon = event.target.textContent;
//Populate it in 1st row input fields (after plus sign)
$("#bonus" + bonusInput++).attr("value", bon);
});
//Manipulate background colors of rows with corresponding tables they were
//selected on hover in and hover out
$("input").hover(
function(event) {
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
let num = $(element).val();
//console.log(num);
if (num) {
//Change input color on hover
$(this).css("backgroundColor", "green");
//Change left table bgcolor on hover
$("#table1 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor", "green");
});
// $("#table2 td").each(function() {
// if ($(this).text() === num) $(this).css("backgroundColor","green");
// });
}
});
},
function(event) {
//Change input color on hover out
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
$(element).css("backgroundColor", "white");
});
//Change left table bgcolor on hover out
$("#table1 td").each(function() {
$(this).css("backgroundColor", "orange");
});
}
);
When you use the .hover()-helper, the event-listeners are created and bound to the items that are available at the moment of creation. All inputs that are created after that are ignored. You have to assign/activate the hover-behaviour for them, when you create/append the new inputs.
//Add row input fields dynamically on button click
// Starting number of inputs
let count = 0;
// Wrapper
const wrapper = document.querySelector('#wrapper');
document.querySelector('#btn').addEventListener('click', () => {
// Increment the count to ensure we have unique inputs
count++;
const container = document.createElement('div');
for (let i = 1; i <= 5; i++) {
let input_index = (count * 5) + i;
// Create new `<input>` element
const input = document.createElement('input');
input.type = 'text';
input.name = input_index;
input.size = '4';
input.id = `inp${input_index}`;
$(input).hover(onInputHoverIn, onInputHoverOut);
container.appendChild(input);
// Optional: add empty whitespace after each child
container.append(document.createTextNode(' '));
}
// Bonus-Input
container.append(document.createTextNode(' + '));
let input_index = count + 1;
// Create new `<input>` element
const input = document.createElement('input');
input.type = 'text';
input.name = `bonus${input_index}`;
input.size = '4';
input.style.marginLeft = '20px';
input.id = `bonus${input_index}`;
$(input).addClass('bonus-input');
$(input).hover(onInputHoverIn, onInputHoverOut);
container.appendChild(input);
wrapper.appendChild(container);
});
//END creating rows dynamically
let currentInput = 0;
let bonusInput = 0;
//Left table on click event
$("#table1 td").on('click',function(event){
if (currentInput >= ((count + 1) * 5)) {
return;
}
currentInput++;
//gets the number associated with the click
let num = $(this).text();
//Populate it in 1st row input fields (before plus sign)
$("#inp" + currentInput).attr("value",num);
});
//Right table on click event
$("#table2").on('click',function(event){
if (bonusInput >= (count + 1)) {
return;
}
bonusInput++;
//gets the number associated with the click
let bon = event.target.textContent;
//Populate it in 1st row input fields (after plus sign)
$("#bonus" + bonusInput).attr("value",bon);
});
//Manipulate background colors of rows with corresponsing tables they were
//selected on on hover in and hover out
function onInputHoverIn(event) {
let parent = $(this).parent();
$(parent.children()).each(function (index, element) {
let num = $(element).val();
let isBonus = $(element).hasClass('bonus-input');
//console.log(num);
if (num) {
//Change input color on hover
$(this).css("backgroundColor","green");
if (!isBonus) {
//Change left table bgcolor on hover
$("#table1 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor","green");
});
} else {
//Change left table bgcolor on hover
$("#table2 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor","green");
});
}
}
});
}
function onInputHoverOut(event) {
//Change input color on hover out
let parent = $(this).parent();
$(parent.children()).each(function (index, element) {
$(element).css("backgroundColor","white");
});
//Change left table bgcolor on hover out
$("#table1 td, #table2 td").each(function() {
$(this).css("backgroundColor","orange");
});
};
$("input").hover(onInputHoverIn, onInputHoverOut);
table {
border-collapse: collapse;
border: 5px solid black;
width: 100%;
}
td {
width: 50%;
height: 2em;
border: 1px solid #ccc;
background-color:orange;
text-align:center;
vertical-align:middle;
font-weight:bold;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Table on the left -->
<div style="width: 140px; float: left;">
<table id="table1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!--2nd table-->
<div style="width: 140px; float: left; margin-left: 12px;">
<table id="table2">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
</tr>
</tbody>
</table>
</div>
<!-- Rows on the right-->
<!-- Make sure each input has a unique id-->
<div style="clear: both;">
<div id="wrapper">
<div>
<input type="text" name="1" size="4" id="inp1" value="">
<input type="text" name="2" size="4" id="inp2" value="">
<input type="text" name="3" size="4" id="inp3" value="">
<input type="text" name="4" size="4" id="inp4" value="">
<input type="text" name="5" size="4" id="inp5" value=""> +
<input class="bonus-input" style="margin-left: 20px;" type="text" name="bonus1" size="4" id="bonus1" value="">
</div>
</div>
<button type="button" id="btn">Add new input group</button>
</div>

Javascript - show and hide table rows with buttons

I'm trying to show/hide table rows with the help of buttons.
With the script I'm using now I'm only I'm only able to make one button and only able to show/hide one row.
I want to make more buttons where each button when pressed will show/hide a row. Also I want the button text to change between Info▼ and Info▲ as the first one does in my script.
If I have understood it correctly I should use classes instead of divs but I tried to do that without result.
If anyone could help me out with my script so I can produce more buttons where each one will show/hide a unique row when clicked on I would be grateful.
http://jsbin.com/tovicefu/1/edit This is a simple version of my layout. So when I press the first info button the row below should appear with one image.
Same with the other info button but it displays another row further below.
My script.
<script>
var button_beg = '<button class="button" onclick="showhide()">', button_end = '</button>';
var show_button = 'Info▼', hide_button = 'Info▲';
function showhide() {
var div = document.getElementById( "hide_show" );
var showhide = document.getElementById( "showhide" );
if ( div.style.display !== "none" ) {
div.style.display = "none";
button = show_button;
showhide.innerHTML = button_beg + button + button_end;
} else {
div.style.display = "block";
button = hide_button;
showhide.innerHTML = button_beg + button + button_end;
}
}
function setup_button( status ) {
if ( status == 'show' ) {
button = hide_button;
} else {
button = show_button;
}
var showhide = document.getElementById( "showhide" );
showhide.innerHTML = button_beg + button + button_end;
}
window.onload = function () {
setup_button( 'hide' );
showhide(); // if setup_button is set to 'show' comment this line
}
</script>
<table>
<tr>
<td> <div id="showhide"></div></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<div id="hide_show">
<img src="alfagel.gif" height="210" width="120"/>
</div>
</td>
<td></td>
<td></td>
</tr>`
<tr>
<td> <div id="showhide"></div></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<div id="hide_show">
<img src="alfagel.gif" height="210" width="120"/>
</div>
</td>
<td></td>
<td></td>
</tr>
</table>
You can use a combination of css and javascript. In this jsBin I used a data-attribute to identify 'hideable' rows.
Css:
tr[data-hide="true"] td {
display: none;
}
Javascript to toggle visibility:
function toggleRowvisibility(e) {
var tbl = document.querySelector('table')
,rows = tbl.rows;
for (var i=0;i<rows.length; i+=1){
var hidable = rows[i].getAttribute('data-hide');
if (hidable) {
rows[i].setAttribute('data-hide', /false/i.test(hidable));
}
}
}

Using Javascript How to loop through a div containing checkboxes and get the value checked from each check box

I have a table with each row containing a cell that has 8 check boxes(Column4)
Here is an example
<table id="enc-assets" class="table">
<thead>
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4(CONTAINS OPTIONS)</th>
</thead>
<tbody>
<tr>
<td id="sc-isrc"></td>
<td id="sc-filename"></td>
<td id="sc-path" hidden></td>
<td id="sc-platforms">
<div id="sc-inline" style="display: inline-block;">
<div >
<div ng-repeat="p in products ">
<label id="enc"><input id="Platform" ng-checked="prod[p.name]" ng-model="prod[p.name]" ng-init="prod[p.name] = true" type="checkbox"/></label>
</div>
</div>
</div>
</td>
<td>
</td>
<td><br/><br/><button id="enqueuebtn" type="button" ng-click="Show(test)" class="btn-primary"></button></td>
</tr>
</tbody>
</table>
I am trying to loop through each row and assign values from each cell into an object .
I am having problems getting the value checked from the cell that contains the 8 check boxes. I can get values from the other cells just fine.
I have tried the following:
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms div div").each(function() {
var platform, selected;
selected = $(this).find('#Platform div label input').checked;
if (selected === true) {
platform = $(this).find('#enc').text();
This is the part that I am not sure if works:
selected = $(this).find('#Platform div label input').checked;
Do I have the correct nesting here to get the values from the check boxes?
Try this:
jsFiddle here
$("#enc-assets tbody tr").each(function() {
var message;
message = new Object();
message.isrc = $(this).find('#sc-isrc').text();
message.path = $(this).find('#sc-path').text();
$("#sc-platforms>div>div").each(function() {
alert( $(this).attr('id') );
var platform, selected;
selected = $(this).find('#Platform');
if(selected.is(':checked')) {
alert('Checked');
}
platform = $(this).find('#enc').text();
alert(platform);
}); //END each #sc-platforms>div>div
}); //END each #enc-assets tbody tr

jQuery on function is getting bound to the container, why so?

I have a simple jquery code
$('tbody').on("click",$('vote'+rowCount),function(){alert('hi');});
but the alert shows up when i click anywhere on the table body instead of just showing up on clicking the selector
Why is this happening?
----Edit---
Got it working by writing the element as "#vote"+rowCount instead of writing as $('vote'+rowCount)
But there is another weird problem -
I am creating dynamic rows with this code, but whatever i type in the value of the textbox remains empty (as initialized), why so
$('#add_ans').click(function(){
var rowCount = $('table tbody tr').length + 1;
var rowString = '<tr>\
<td><div class="span_5"><span class="badge badge-success">'+rowCount+'</span></div></td>\
<td><div class="span3"><input type="text" class="input-large" value="" /></div></td>\
<td><div class="span2 pull-right"><b>0</b></div></td>\
<td><div class="span2"><button class="btn btn-success" id="vote'+rowCount+'"><b>Vote!</b> <i class="icon-thumbs-up"></i></button></div></td>\
<td><div class="span2"><button class="btn btn-info" disabled><b>Reviews</b> <i class="icon-ok-circle"></i></button></div></td>\
</tr>'
$('tbody').append(rowString);
$('tbody').on("click","#vote"+rowCount,voteOption);
});
and the event handler is
function voteOption(){
var rowCount = $('tr').index($(this).closest('tr'));
alert(rowCount);
var ans = $('tr:eq('+rowCount+') .input-large').attr('value');
alert(ans);
}
This is because the second argument is selector (string), not an element selected by $().
$('vote'+rowCount) is not correct and the .on() click event will be fired anywhere you click because the .on event is actually bind to the <tbody>.
For example, this will match the <div> inside the <tbody> and bind the click event to it.
$('tbody').on("click", 'div' ,function(){alert('hi');});
Here is the code example....
HTML
<input type="button" id="createBtn" value="Create"/>
<table id="mytable">
<tbody id="mytableBody">
</tbody>
</table>
JavaScript
$(document).ready(function()
{
var i = 0;
$("#createBtn").click(function()
{
var newRow = $("<tr></tr>").attr("id", "row"+i);
var btn = $("<button>Vote</button>").attr("id", "vote"+i);
var col = $("<td><span>Video "+i+"</span></td>");
col.append(btn);
newRow.append(col);
$("#mytable tbody").append(newRow);
i++;
});
$('#mytable tbody').on("click", "button", function(){
alert(this.id);
if(this.id == 'vote0')
{
alert("Thanks for voting for video 0.");
}
else if(this.id == 'vote1')
{
alert("Thanks for voting for video 1.");
}
else
{
// handle the rest....
}
});
});
You can also find this in jsfiddle http://jsfiddle.net/33Wny/1/

Categories