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;
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.