Select option comparing with Table Row - javascript

I have this button to append a <Select> but the option should not be showing what is already in the table row (Math, English, Science) So I needed to only Show the PE SUBJECT in the <select> options, I tried doing the .each in JQuery but I cant compare the two. I'm trying to make my table dynamic.
This is my sample JSFiddle https://jsfiddle.net/ta73h4ez/16/
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<script>
$( document ).ready(function() {
$( "#add" ).click(function() {
$('tbody').append('<tr><td><select><option value="math">Math</option><option value="English">English</option><option value="Science">Science</option><option value="PE">PE</option></select></td><tr>');
});
});
</script>
<h2>HTML Table</h2>
<table>
<tbody>
<tr>
<th>Subject</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
<tr>
<td>Math</td>
<td>8am</td>
<td>9am</td>
</tr>
<tr>
<td>English</td>
<td>10am</td>
<td>1pm</td>
</tr>
<tr>
<td>Science</td>
<td>1pm</td>
<td>3pm</td>
</tr>
</tbody>
</table>
<input type="button" value = "Add Subject" id ="add">
</body>
</html>

you can compare like :
$('table').find('tr').each(function(){
var td1=$(this).find('td').eq(0).text();
$('select').find('option').each(function(){
var op = $(this).text();
if(op==td1)
{
$(this).hide();
}
});
});
This is my sample JSFiddle
jsFiddle

Change your javascript function to below. You can optimize this code according to your requirements.
$( document ).ready(function() {
$( "#add" ).click(function() {
var options = getOptions();
var optionsString = "";
for(var i = 0; i< options.length; i++){
optionsString += '<option value="'+options[i]+'">'+options[i]+'</option>';
}
$('tbody').append('<tr><td><select>'+optionsString +'</select></td><tr>');
});
var getOptions = function(){
var options = ["Math", "English", "Science", "PE"];
var allRows = $('table').find('tr');
for(var i=0; i< allRows.length && options.length>0; i++){
var subjectText = $(allRows[i]).find('td').eq(0).text();
var index = options.indexOf(subjectText);
options = options.splice(index, 1);
}
return options;
};
});

Related

When TR is clicked, then check the checkbox

When I click it for the first time, it click, but doesn't turn off...
I've tried this one, it checked and uncheck but only once.
This one doesn't work for me either.
$(document).ready(function() {
$("tr").click(function() {
var checkbox = $(this).find("input[type=checkbox]");
if (!checkbox.prop("checked", "")) {
checkbox.prop("checked", "false");
} else {
checkbox.prop("checked", "true");
}
});
});
td{
background:red;
padding:10px 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="checkbox" />
</td>
<td>test</td>
</tr>
</table>
Here is a toggle
$(document).ready(function() {
$("tr").on("click", function(e) {
const $target = $(e.target)
const $checkbox = $(this).find("input[type=checkbox]");
// only run code when NOT clicking checkbox
if (!$checkbox.is($target)) {
let checked = $checkbox.is(":checked")
$checkbox.prop("checked", !checked)
}
});
});
td {
background: red;
padding: 10px 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="checkbox" />
</td>
<td>test</td>
</tr>
</table>

Read values from text field individually

I would like to read all values from a text field/text box individually and then write them to a table:
Example:
This is an example of a text I want to read out.
Output:
This
is
an
example
of
a
text
I
want
to
read
out
How can I use a loop to read the text field/textbox?
That is, whenever a space comes the new subsequent value must be in a new line.
String:
var table = document.getElementById("table");
var phrase = "This is an example of a text I want to read out";
var words = phrase.split(" ");
for (var i = 0; i < words.length; i++) {
var tableCol =
`<tr>
<td>${i+1}:</td>
<td>${words[i].replace(/[\.,!\?]/g," ")}<td>
</tr>`;
document.querySelector('table tbody').innerHTML += tableCol;
}
#table {
border: 1px solid;
}
th {
border: 1px solid;
padding: 5px;
}
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>
Input:
var table = document.getElementById("table");
var myBtn = document.getElementById("myBtn");
var myInput = document.getElementById("myInput");
myBtn.addEventListener('click', () => {
document.querySelector('tbody').innerHTML = '';
var phrase = myInput.value;
var words = phrase.split(" ");
for (var i = 0; i < words.length; i++) {
var tableCol =
`<tr>
<td>${i+1}:</td>
<td>${words[i].replace(/[\.,!\?]/g," ")}<td>
</tr>`;
document.querySelector('tbody').innerHTML += tableCol;
}
});
input {
margin-bottom: 10px;
width: 300px;
height: 25px;
}
#table {
border: 1px solid;
}
th {
border: 1px solid;
padding: 5px;
}
<input id="myInput" type="text">
<button id="myBtn">Create Table</button>
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>
Shorter and removing punctuation
const str = `This is an example of a text I want to read out.`;
document.querySelector('table tbody').innerHTML = str.split(" ")
.map((word,i) => `<tr><td>${i+1}:</td><td>${word.replace(/[\.,!\?]/g,"")}<td></tr>`)
.join("");
<table id="table">
<thead>
<th>Number:</th>
<th>Word:</th>
<thead>
<tbody>
</tbody>
</table>

How to toggle the checkbox while the user clicks on the row where the checkbox resides in?

I have a table with 2 columns, the first column shows the text, and the other column has a checkbox.
The code is as follows, and the checkboxes are generaged by JavaScript, e.g. var checkbox = document.createElement("input");
<script type="text/javascript">
function create_table() {
var data = ["Sandwidch", "Hamburger", "Bacon"];
var table = document.getElementById("menu");
for (var option in data) {
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = data[option];
var cell2 = row.insertCell(1);
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "choiceCbx";
cell2.appendChild(checkbox);
}
}
window.onload = create_table;
</script>
<body>
<table id="menu">
<tr>
<th>Food</th>
<th>Choice</th>
</tr>
</table>
</body>
When the user clicks on one of the rows in the table, if the checkbox on the row was checked, it should become unchecked, and vice versa.
I used the following code to toggle the checkbox but in vain, it seems just detects the "TH" row, but not the "TR" rows:
$(document).ready(function() {
$('#menu tr').click(function(event) {
if (event.target.type !== 'checkbox') {
$(':checkbox', this).trigger('click');
}
});
});
How should I modify my code to make the toggle function work?
you can do that...
const table_foods = document.querySelector('#records tbody')
table_foods.onclick=e=>
{
if (e.target.matches('input[type=checkbox]')) return // to not disturb natural check action
let chkBx = e.target.closest('tr').querySelector('input[type=checkbox]')
chkBx.checked = !chkBx.checked
}
/* cosmetic part */
table {
border-collapse: collapse;
margin-top: 25px;
font-family: Arial, Helvetica, sans-serif;
font-size: 14px;
}
thead {
background-color: aquamarine;
}
tbody {
background-color: #b4c5d8;
}
td, th {
border: 1px solid grey;
padding: .3em .7em;
}
<table id="records" class="content">
<thead>
<tr> <th>Food</th> <th>Choice</th> </tr>
</thead>
<tbody>
<tr>
<td>Sandwitch</td>
<td><input type="checkbox" name="answerCbx-1" /></td>
</tr>
<tr>
<td>pizza</td>
<td><input type="checkbox" name="answerCbx-2" /></td>
</tr>
</tbody>
</table>
Try this. Also you might want to add more details to your question because the HTML does not contain any checkboxes
https://forum.jquery.com/topic/toggle-checkboxes-in-a-table-after-click-function

Creating table with counter

I have the following code and am trying to get the number entered by the user to create that amount of rows with a counter in the cells up to the number entered(ie. if user enters 6, 6 rows will appear with 1-6 in them, 1 at the top) I figure a for-loop would work well, but I can't figure out what variables work. Any help would be greatly appreciated!
$(document).ready(function() {
$('#nbrTxt').focus();
var index = 1;
$('input[name=nbrTxt]').on('keyup', function(e) {
if (e.which === 13) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html($(this).val());
$('table tr:last td:last').html(index);
$(this).focus().select();
index++;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title> JQuery Selector</title>
<style type="text/css">
body {
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
</style>
<script src="jquery-1.11.3.min.js"></script>
<script src="jqueryselector.js"></script>
</head>
<body>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name= "nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo"/>
<table id="table" width="500" border="1">
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</table>
</body>
Try this. I just changed keyup event to click though, but it should work.
$(document).ready(function() {
$('#nbrTxt').focus();
$('#btnGo').on('click', function(e) {
var value = $('#nbrTxt').val();
for (var i = 1; i <= value; i++) {
$('table').append('<tr><td></td><td></td></tr>');
$('table tr:last td:first').html(value);
$('table tr:last td:last').html(i);
}
});
});
Yes, you can use a for loop.
$(document).ready(function() {
$('#nbrTxt').focus();
$('input[name=nbrTxt]').on('keyup', function(e) {
var index = parseInt($(this).val());
if (e.which === 13) {
for(var i = 1; i <= index; i++) {
$('table').append('<tr><td>' + i + '</td><td></td></tr>');
$(this).focus().select();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<title> JQuery Selector</title>
<style type="text/css">
body {
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
</style>
<script src="jquery-1.11.3.min.js"></script>
<script src="jqueryselector.js"></script>
</head>
<body>
<h1>JQuery Selector</h1>
Enter Number:
<input type="number" name= "nbrTxt" id="nbrTxt" />
<input type="button" value="GO" id="btnGo"/>
<table id="table" width="500" border="1">
<tr>
<td>No. Count</td>
<td>Name</td>
</tr>
</table>
</body>

Table and mouse rollover effect (hover)

I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/
If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();
below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered
would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>
I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}
for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code
Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});

Categories