i am struggling to get it to work since this is my first try making something on my own.
I want to take input from the input field inside the form, click the submit button, and on each row i want a new input[type='text'] in a table.
for example: david, jan, mark
each of the above names needs to be added on a new row separetly, randomly chosen, below each other
hope this makes sense.
in the example below, it adds the input next to each other.
// when the page is loaded
// hiding the table in the DOM = document object model
$(document).ready(function() {
$('.table').hide();
});
// Get input from 'inputNames' text area
$('#button').click(function() {
var name = $('input[type="text"]').val().split(',');
// checking to see if the "input[type='text']" value is empty
if ($('#inputNames').val() !== '') {
// iterate over de names
$('#inputNames').each(function() {
for (var i = 0; i < name.length; i++) {
name[i];
//Create a new td add to tr
$('.inserted').append('<td>' + name[i] + '</td>');
}
});
// log the variable name to see the object
console.log(name);
// slide in the table
$('.table').fadeIn(2500);
// without it wont load the fadeIn effect
return false;
} else {
alert('You need to fill in the input field');
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Roulatie Schema</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>Roulatie Schema</h1>
<p class="lead">Gewoon een simpel roulatie schema, waarbij alleen de namen van de betreffende mensen hoeft te worden ingevuld</p>
<hr class="my-4">
<form id="myForm">
<div class="form-group">
<label for="inputNames">Fill in the names separated by a comma</label>
<input type="text" class="form-control" id="inputNames" required='true' aria-describedby="emailHelp" placeholder="Example name, name">
<small id="emailHelp" class="form-text text-muted">the field above can not be empty!!</small>
</div>
<button id="button" type="submit" class="btn btn-primary btn-lg">Submit</button>
</div>
<table class="table" align='center'>
<thead class="thead-dark">
<tr>
<th>#Rounds</th>
<th>#First Round</th>
<th>#Second Round</th>
<th>#Third Round</th>
</tr>
</thead>
<tbody>
<tr class="inserted">
<td>Luxe lades</td>
</tr>
<tr class="inserted">
<td>Meta lades</td>
</tr>
<tr class="inserted">
<td>Inpak</td>
</tr>
<tr class="inserted">
<td>Controle 100%</td>
</tr>
<tr class="inserted">
<td>Lades inhangen</td>
</tr>
<tr class="inserted">
<td>Deuren</td>
</tr>
<tr class="inserted">
<td>Planken</td>
</tr>
<tr class="inserted">
<td>Panelen</td>
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Ok, so this answer has two steps, in the hope that I understood what you want to do correctly.
Step #1:
You are currently fishing the names properly but instead of adding them to the table in new rows you just add them as cells to each and every row. So changing the append() content can fix that:
$('#inputNames').each(function() {
for (var i = 0; i < name.length; i++) {
name[i];
$('tbody').append('<tr class="inserted"><td>' + name[i] + '</td></tr>');
}
});
Step #2:
Now you want them to be added randomly. There are many ways to go about this but I will just offer one, which in the code actually comes before the 1st step:
randomize the name array.
how? simple:
var name = $('input[type="text"]').val().split(',');
name.sort(function(a, b){return 0.5 - Math.random()});
notice you do not to set name=name.sort() the method already sets it for you.
Now the code takes the names, randomizes them, and appends them as new rows in the table.
Related
I am trying to filter through dynamically inserted "td" elements in the table element within the HTML. I want the user to be able to type in text within the filter input field and if the text matches any of the td elements text content I want to those td elements displayed. I created the "filter" method within the "Music" constructor the last method within the constructor, furthermore, I called the filter method within the "filter field event listener" the last bit of code in the script. Any help would be appreciated. Thanks (I understand this is a lot of code but I wanted to give some context to my question!)
//JavaScript
// Music Constructor
class Music {
constructor(artist, song, album, genre) {
this.artist = artist;
this.song = song;
this.album = album;
this.genre = genre;
}
// Add song to music list
addSongToList(music) {
// Select Music List in UI
const list = document.querySelector('#music-list');
//Create Element
const row = document.createElement('tr');
row.className = 'row-data';
row.innerHTML =
` <td class="tbl-data">${music.artist}</td>
<td class="tbl-data">${music.song}</td>
<td class="tbl-data">${music.album}</td>
<td class="tbl-data">${music.genre}</td>`;
list.appendChild(row);
}
// Clear Fields
clearFields() {
artist.value = '';
song.value = '';
album.value = '';
genre.value = '';
}
// Delete Song
deleteSong(target) {
if (target.className === 'tbl-data') {
target.parentElement.remove();
}
}
//Filter songs by genre
filter(input) {
let songs = document.querySelectorAll('td');
songs.forEach(function(song) {
let songRow = song.textContent;
if (songRow.toLowerCase().includes(input)) {
song.style.display = 'block';
}
})
}
// Welcome message
static welcomeMsg(message, className) {
// Create element
const div = document.createElement('div');
div.className = 'welcomeMessage';
div.appendChild(document.createTextNode(message));
// Select parent
const parent = document.querySelector('.container');
const card = document.querySelector('.card');
parent.insertBefore(div, card);
setTimeout(function() {
div.remove();
}, 6000);
}
}
// Document object event listener
document.addEventListener('DOMContentLoaded', function() {
// Welcome Message call
Music.welcomeMsg('Welcome, enter your favorite artist, songs, albums, and genre in the input fields below! Double click songs you want to delete once added!');
})
// Event listener on Form
document.querySelector('form').addEventListener('submit', function(e) {
// UI Form Input
const artist = document.querySelector('#artist').value;
const song = document.querySelector('#song').value;
const album = document.querySelector('#album').value;
const genre = document.querySelector('#genre').value;
//Instantiate Music Constructor
const music = new Music(artist, song, album, genre);
console.log(music);
// Call prototype method
music.addSongToList(music);
music.clearFields()
e.preventDefault();
})
// Music list event listener
document.querySelector('#music-list').addEventListener('dblclick', function(e) {
//Instantiate Music Constructor
const music = new Music(artist, song, album, genre);
//Remove method call
music.deleteSong(e.target);
});
// Filter field event listener
document.querySelector('#filter').addEventListener('keyup', function() {
let filter = document.querySelector('#filter').value;
//Instantiate Music Constructor
const music = new Music(artist, song, album, genre);
// Call filter prototype method
music.filter(filter);
});
//HTML
<body>
//Container with the input fields
<div class="primary-container ">
<div class="container">
<h1 class="text-center mb-3">Favorite Music Archive</h1>
<div class="card mx-auto px-4">
<form action="">
<label for="basic-url" class="form-label form-text">Music Artist</label>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon3"><img src="icons/guitar.png" alt="artist" class="icon-img"></span>
<input type="text" class="form-control" id="artist" placeholder="Enter Musical Artist">
</div>
<label for="basic-url" class="form-label form-text">Song</label>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon3"><img src="icons/music.png" alt="song" class="icon-img"></span>
<input type="text" class="form-control" id="song" placeholder="Enter Song">
</div>
<label for="basic-url" class="form-label form-text">Album</label>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon3"><img src="icons/music-album.png" alt="Album" class="icon-img"></span>
<input type="text" class="form-control" id="album" placeholder="Enter Album or Single">
</div>
<label for="basic-url" class="form-label form-text">Genre</label>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon3"><img src="icons/dj.png" alt="genre" class="icon-img"></span>
<input type="text" class="form-control" id="genre" placeholder="Enter Genre">
</div>
<div class="d-flex justify-content-center p-3">
<button type="submit" class="subBtn">Submit Song</button>
</div>
</form>
</div>
</div>
</div>
<div class="second-container">
//Filter Input field
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1"><img src="icons/filter.png" alt="filter" class="icon-img"></span>
<input type="text" class="form-control filter-input" placeholder="Filter by genre" id="filter"> //Filter Input End
<table class="table table-dark table-striped">
<thead>
<tr class="row-head">
<th scope="col">Artist</th>
<th scope="col">Song</th>
<th scope="col">Album</th>
<th scope="col">Genre</th>
</tr>
</thead>
// Dynamically inserted TD elements will go into tbody
<tbody id="music-list">
</tbody>
</table>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
The easiest way to search a table (if you are open to using JQuery) is to use JQuery DataTables. It allows you to search a table quite easily. All you have to do is include JQuery and the JQuery DataTable CDN to get it working:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<link rel="stylesheet" type="text/css" crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" crossorigin="anonymous" href="//cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
<script src="//cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js" crossorigin="anonymous"></script>
</head>
<body>
<table id="myTable" class="table table-secondary table-striped">
<thead>
<tr class="row-head">
<th scope="col">Artist</th>
<th scope="col">Song</th>
<th scope="col">Album</th>
<th scope="col">Genre</th>
</tr>
</thead>
<tbody>
<tr>
<td>Some artist 1</td>
<td>Some song 1</td>
<td>Some album 1</td>
<td>Some genre 1</td>
</tr>
<tr>
<td>Some artist 2</td>
<td>Some song 2</td>
<td>Some album 2</td>
<td>Some genre 2</td>
</tr>
<tr>
<td>Some artist 3</td>
<td>Some song 3</td>
<td>Some album 3</td>
<td>Some genre 3</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function(){
// Initiate the data table:
$("#myTable").DataTable();
});
</script>
</body>
</html>
All you do is initiate it as a DataTable and it will automatically provide a search input (that live searches the table), "Show X Entries", "Showing X to Y of Z entries", and pagination. Now, you can customize it further to only show the input search box if you would like, but I will refrain from further elaboration unless you are interested.
This will also work for any dynamically created td tags. If you are only dynamically inserting td tags before user interaction with the table (so right on render), then you can simply initialize the table ($("#myTable").DataTable();) after you are done dynamically creating the table's tbody. If you are steadily inserting td tags even after the table has been rendered for the user to use, then you can add rows dynamically and redraw the DataTable:
let table = $("#myTable").DataTable();
// This adds a new row after the DataTable was already rendered:
table.row.add([
"Some artist 4",
"Some song 4",
"Some album 4",
"Some genre 4"
]);
// This redraws the DataTable to reflect those changes:
table.draw();
I am trying to display a hidden table in a div then hide it again with display: none/block toggle. It works. But, I can't get it to appear again once I toggle to display: none to hide it.
HTML:
The HTML has an empty div with id = tableContainer.
Next to it, I have a table with the names of animal families in each cell, along with a button. When the button is clicked, it takes the name of the animal family from that particular cell, finds the table of animal species with that name and switches from display: none to display:block and display it /inside the div. Then, if I click the button again, it toggles the display back to display: none.
When I click a button in another cell, it clears the div and displays the new table.
All good.
But, if I click a button that was previously used, the table that has now gone is no longer available.
I have gone through all sorts of hoops playing with removeChild and all that but no luck. I am currently using innerHTML to clear the div, but I'm missing something with the class name.
Console error says: tabletest2.html:523 Uncaught TypeError: Cannot read property 'classList' of null
at toggle (tabletest2.html:523)
at HTMLButtonElement.onclick (tabletest2.html:72)
So, it seems to me that it can't toggle any more because the table now no longer exists, or I may be wrong with that as I didn't delete the child element (I think).
<body>
<table>
<tbody>
<tr>
<td>Genus</td>
<td>Benthobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
</tbody>
</table>
<!-- <======== div display container here ================>-->
<div id="tableContainer"></div>
<table id="Benthobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th>Benthobatis</th>
</tr>
<tr>
<td>Benthobatis kreffti</td>
<td>Brazilian Blind Electric Ray</td>
</tr>
</tbody>
</table>
<!-- <==================================-->
<table id="Diplobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th> Diplobatis </th>
</tr>
<tr>
<td>Diplobatis colombiensis</td>
<td>Colombian electric ray</td>
</tr>
</tbody>
</table>
</body>
<script>
function toggle(ele, tableName) {
var myTableDisplayDiv = document.getElementById("tableContainer").childNodes;
if (myTableDisplayDiv.length != 0) {
document.getElementById("tableContainer").innerHTML = "";
}
var myTableName = tableName.textContent;
var myTable = document.getElementById(myTableName);
myTable.classList.toggle("hide");
document.getElementById("tableContainer").appendChild(
document.getElementById(myTableName)
);
}
</script>
<style>
.hide {
display: none;
}
Explanations
"Why are my tables deleted if I'm only changing display option, not removing the child node?".
This destroys everything within:
document.getElementById("tableContainer").innerHTML = "";
This moves the chosen table to #tableContainer:
document.getElementById("tableContainer").appendChild(
document.getElementById(myTableName)
So in three clicks there's nothing left. Of course this is if the table can be identified correctly which it wasn't. The .textContent of .parentNode.firstChild reference was lost because this refers to a global context not the button. This is why on-event attributes (among other various reasons) are discouraged. Although not a critical issue as the ones previously mentioned, you should seriously have some variations to the names:
tableName
myTableName
myTable
myTableDisplayDiv
tableContainer
I'm pretty sure this naming scheme did not facilitate debugging.
Solutions
Before you place a table into #tableContainer where it gets destroyed, make a copy with .cloneNode().
Remove the onclick attributes and either use onclick property (like in the demo) or .addEventListener().
Register an ancestor element of both buttons (i.e. tbody), from there both buttons can be clicked and easily isolated and referenced by using event.target.
Now the reference to the clicked button (event.target) can now be referenced:
var tableName = event.target.parentNode.firstChild.textContent
And then the table can finally be referenced:
var table = document.getElementById(tableName)
Demo
document.querySelector('tbody').onclick = toggle;
function toggle(event) {
var clicked = event.target;
if (clicked.tagName === 'BUTTON') {
var genus = clicked.parentNode.firstChild.textContent;
var table = document.querySelector('#' + genus);
var display = document.getElementById("display");
display.innerHTML = "";
var clone = table.cloneNode(true);
display.appendChild(clone);
clone.classList.toggle('hide');
}
}
.hide {
display: none;
}
<table>
<tbody>
<tr>
<td>Genus</td>
<td>Benthobatis
<button>Click me</button></td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis
<button>Click me</button></td>
</tr>
</tbody>
</table>
<!-- <======== div display container here ================>-->
<div id="display"></div>
<table id="Benthobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th>Benthobatis</th>
</tr>
<tr>
<td>Benthobatis kreffti</td>
<td>Brazilian Blind Electric Ray</td>
</tr>
</tbody>
</table>
<!-- <==================================-->
<table id="Diplobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th> Diplobatis </th>
</tr>
<tr>
<td>Diplobatis colombiensis</td>
<td>Colombian electric ray</td>
</tr>
</tbody>
</table>
Your code is kind of complex to understand but if you just want to toggle the table, I think this is the best way.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<div class="table-container">
<button class="toggle-btn">Click me</button>
<table>
<tr>
<td>Genus</td>
<td>Benthobatis</td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis</td>
</tr>
</table>
</div>
<script>
const table = document.querySelector('table'),
btn = document.querySelector('.toggle-btn');
btn.addEventListener("click", () => {
table.classList.toggle("hide")
})
</script>
</body>
</html>
I am new to angularjs and stuck with the below problem.
There will be a table of rows created which reads data from JSON. Say there are 6 rows displayed.But in real time number rows will vary.
Each row has an accordion(+ symbol) in its first td. If this accordian is clicked then the children rows of that row should be displayed by reading the data from one more different JSON.
Similarly for the remaining 5 rows as well it should display the children rows for the respective row's accordion is clicked.
I have created the table with the 6 rows displayed.
But the challenge I am facing is how to link child rows to the existing rows dynamically when clicked. Here is the plunkr - https://plnkr.co/edit/FTbjn9ZbAOTqc3b6j52h?p=preview
Any help is appreciated.
<html>
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css"/>
<link rel="stylesheet" href="font-awesome.min.css"/>
<link rel="stylesheet" href="bootstrap.min.css" />
</head>
<body data-ng-app="testApp" data-ng-controller="treeTable">
<hr>
<button type="button" class="btn btn-success" data-dismiss="modal" data-ng-click="save()">SaveFilter</button>
<button type="button" class="btn btn-Default" data-dismiss="modal" data-ng-click="delete()">Delete</button>
<div class="row">
<div class="col-md-9">
<div style=" margin-left:50px;" class="tableheight">
<table class="table-nested ">
<thead>
<tr>
<!-- <th >
<input data-ng-checked="(list | selected).length == list.length" data-ng-click="toggleAllCheckboxes($event)" type="checkbox" />
</th> -->
<th>
Repository
</th>
<th >
Version
</th>
<th >
Size
</th>
<th >
Modified By
</th>
<th >
Labels
</th>
<th >
Description
</th>
</tr>
</thead>
<tbody style="font-size:12px" data-ng-repeat="item in list">
<tr >
<td ><button style="background-color: #fff;" class="accordion"></button>
{{item.name}}
</td>
<td >
{{item.Version}}
</td>
<td >
{{item.Size}}
</td>
<td >
{{item.ModifiedBy}}
</td>
<td >
{{item.Labels}}
</td>
<td >
{{item.Description}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
See the Plunkr solution
You want a 2nd <tr> with ng-repeat following the first:
<tr ng-if="item.Labels==child.Labels" ng-show="item.opened" ng-repeat="child in children">
<td>{{child.name}}</td>
...etc
</tr>
This will build additional rows where the bundle .Labels matches the repo .Labels and will be shown only when the repo's opened property is true. The + button will toggle the opened property for each item. You'll need two minor edits to your data to make this work:
Add children data to the $scope (for access in the 2nd ng-repeat).
Add default opened: false property to all repos (except the first, which is true).
This won't show the components, but hopefully you get the idea.
See the Plunkr solution
If you want to inset row after row clicked use this:
<style>
#tableid {
font-size: 14px;
}
#tableid .childRow {
font-size:10px;
}
#tableid .childRow td:first-of-type {
padding-left:10px;
}
</style>
<table id="tableid">
<tr onclick="AddRow(this)">
<td>abcd</td>
</tr>
</table>
<script>
function AddRow(e)
{
for (var i = 0; i < 5; i++)
{
var index = e.rowIndex;
var table = document.getElementById("tableid");
var row = table.insertRow(index + 1 + i);
row.setAttribute('class', 'childRow');
var cell = row.insertCell(0);
cell.innerHTML = "efgh";
}
}
</script>
I'll try and state what im trying to do and hope it makes sense (i only learned this last week!). When clicking the delete button that i create, i would like the content associated along with it to go down into a panel body i created in my HTML page with a class name of 'panelAdd'. Any help is much appreciated as i am quite new. Thanks for reading. Ill put the HTML first
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/darkly/bootstrap.css" crossorigin="anonymous" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>To Do List</title>
</head>
<body>
<h3 class="header">
<strong>To Do List</strong>
</h3>
<table class="table table-responsive myTable col-xs-offset2" id="myTable">
<thead>
<th>Complete?</th>
<th>Task to Complete</th>
<th>Time to Complete?</th>
<th>Remove?</th>
</thead>
<tbody>
<tr>
</tr>
<tr>
<td><input type="checkbox" class="newCheck col-xs-offset-2" value=""></td>
<td><input type="text" class="newWord" placeholder="New task"></td>
<td><input type="text" class="newTime" placeholder="How long do you have?"></td>
<td><button class="btn btn-primary buttonAdd">Add Task</button></td>
</tr>
</tbody>
</table>
<footer>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Completed!</h3>
</div>
<div class="panel-body"></div>
</div>
</footer>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/add.js"></script>
<script type="text/javascript" src="js/remover.js"></script>
</body>
</html>
Add button
$(document).ready(function (){
$(".btn-primary").on("click", function(e) {
e.preventDefault();
var newWord, newRow, wordTd, newCheck, deleteButton, deleteTd;
var isDuplicate;
newWord = $(".newWord").val();
newTime = $(".newTime").val();
newCheck = $(".newCheck").val();
var newRow = $("<tr>");
var newCheck = $("<input>").attr("type", "checkbox").attr("class", "newCheck").attr("data-state", "not-checked");
var wordTd = $("<td>").append(newWord).before();
var timeTd = $("<td>").append(newTime).before();
var deleteButton = $("<button>").addClass("btn btn-danger buttonRemove").append("Remove");
var deleteTd = $("<td>").append(deleteButton);
newRow.append(newCheck).append(wordTd).append(timeTd).append(deleteTd).before();
$("tbody").append(newRow);
$("#newWord").val("")
});
});
$(document).on("click", ".newCheck", function(){
if($(this).prop("checked") === true){
$(this).parent().attr("class", "done");
}
else{
$(this).parent().removeClass();
}
});
Remove Button
$(document).ready(function (){
$(document).on("click",".btn-danger", function(){
$(this).parents("tr").remove();
});
});
FIDDLE
Remove Button
$(document).on("click",".btn-danger", function(){
$t = $(this).closest('tr').find('td')[0];
$(this).parents("tr").remove();
$('.panel-body').append($t);
});
});
What you can do is grab the content you want to insert and append it in the target panel in this case .panel-body. See the fiddle above which adds the task name to the Completed list.
Do you expect like this.
Fiddle Sample
Code snippets:
$(document).on("click",".btn-danger", function(){
var removed = $(this).parents("tr").remove();
$(".panel-body").append('<div class="panelAdd"></div>').append(removed);
});
Let me know if this helps!
DEMO
You can just use .detach and .appendTo on click event of your remove button as below:
$(document).on("click",".btn-danger", function(){
var detachedRow=$(this).parents("tr").detach(); //detach and store it as reference
detachedRow.find('input[type="checkbox"]').remove();
//I hope you don't need checkbox when task is complete so removing it from that row
detachedRow.appendTo($('.panel .panel-body #myTableCompleted tbody'));
append it to your completed panel
});
Note : The .detach() method is the same as .remove(), except that
.detach() keeps all jQuery data associated with the removed elements.
This method is useful when removed elements are to be reinserted into
the DOM at a later time.
I have also added the table structure in your .panel-body to get the same UI look and have removed column for checkbox from the same and it is as below:
<div class="panel-body">
<table class="table table-responsive myTable col-xs-offset2" id="myTableCompleted">
<thead>
<th>Task to Complete</th>
<th>Time to Complete?</th>
<th>Remove?</th>
</thead>
<tbody>
</tbody>
</table>
</div>
Note - I think there might be other requirements too like only checked
checkbox to be added to that completed panel-body etc., and if yes
there will be a minor change in the delete code
I'm trying to implement a function for a dinamic table, the table starts like this:
<table>
<thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
<tbody id="bodyVender">
<tr>
<td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
</tr>
</tbody>
</table>
And then i'm adding more table rows to the tbody when the JQuery function is called, like this:
$('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');
As you can see, the new row created will have tds and inputs with a new ID determined by the "count" variable, so that input ID could look like: inp0 , inp1, inp2 after each function call.
This works, but just the first time, even when I'm calling the function for that new created ID.
I'm using $(document).on to call the function, and I think that should work for the new row created.
Here's the entire code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Panel de Administración</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="estilo3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(Principal);
function Principal(){
var count = 0; //sell's counter
$(document).on('keydown','#inp'+String(count), function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
function VenderConsulta(Codigo,ntd){
datos={codigo:Codigo}; // the code to send
$.ajax({
url:"bringMeTheData.php",
type: "POST",
data: datos,
success: function(datos){
console.log(datos); //i'm recibing something like [{"Nombre":"A product name","P_venta":"990"}]
count+=1; //next time i'll choose the new input with id="inp1"
$(':focus').blur(); //blur the input
var arr = JSON.parse(datos);
var tdNombre = arr[0].Nombre;
var tdPrecio = arr[0].P_venta;
$('#tdN'+ntd+'').html(tdNombre);
$('#tdC'+ntd+'').val(1);
$('#tdP'+ntd+'').html(tdPrecio);
$('#bodyVender').append('<tr><td><input id="inp'+count+'" type="text" class="form-control"></td> <td id="tdN'+count+'"></td> <td><input id="tdC'+count+'" type="text" class="form-control"></td> <td id="tdP'+count+'"></td></tr>');
$('#inp'+count).focus(); //setting focus to the new created input
}
});
}
}
</script>
</head>
<body>
<div class="container-fluid">
<section class="tablaVender">
<div class="row">
<div class="table-responsive" style="background:white">
<h3 style="margin-left:15px"> Venta de productos </h3>
<table class='table table-hover table-bordered'>
<thead><tr><th>Código</th><th>Nombre</th><th>Cantidad</th><th>Precio</th></tr></thead>
<tbody id="bodyVender">
<tr> <!-- This is the input and i'll add more trs like this in the function VenderConsulta -->
<td><input id="inp0" type="text" autofocus="true" class="form-control"></td> <td id="tdN0"></td> <td><input id="tdC0" type="text" class="form-control"></td> <td id="tdP0"></td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Why this works just the first time and then no more? I'm working wrongly with that new row created?
Sorry for my bad english and thanks.
Your selector for the keydown function will only trigger it for the first input. You only call .on() once, and you give it '#inp'+String(count) as the selector. Your variable count is 0 at that point, so it will only work with the input that has the id inp0. You could fix this by using a selector that will work with all input[x] ids. And attribute selector that checks the beginning of the id would work. Like:
$(document).on('keydown','[id^=inp]'function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
It's because this code:
$(document).on('keydown','#inp'+String(count), function(e){ //when press key on input with id="inp0"
if(event.keyCode == 13){ //if the key pressed is Enter
VenderConsulta($(this).val(),count); //call function VenderConsulta with the typed code
}
});
will only get executed once, and when it does, the value of count is 0. So you're only binding the event to the first element.
Instead, you should probably use a class to target those elements.