Suppose I have the following structure:
<div id="table">
<div class="row">
<div class="cell">a</div>
<div class="cell">b</div>
</div>
<div class="row">
<div class="cell">d</div>
<div class="cell">c</div>
</div>
</div>
How do I reiterate through them in a way that I create the same structure but with <table> instead of <div id="table">, <tr> instead of <div class="row"> and <td> with the content of the div instead of <div class="cell">;
I tried doing something like
let topics_table = '<table>'
$('#table > .row').each(function(){
topics_table += '<tr>'
$(this + ' .cell').each(function(that){
topics_table += '<td>' + that.text() + '</td>'
})
topics_table += '</tr>';
})
topics_table += '</table>`
But I get an error...
$(this + ' .cell')
Should be
$(this).find('.cell')
// or
$('.cell', this)
You're trying to concatenate a string to a DOM Element.
.each(function(that){
topics_table += '<td>' + that.text() + '</td>'
})
^^ that is also an issue, because jQuery passes the index in as the first argument, not the element.
.each(function(index, that){
topics_table += '<td>' + that.innerText + '</td>'
})
Related
JSFiddle Here
I have 2 div in HTML
The first div for the folder column.
<div class="columnFolder-container"></div>
The second div for the column table. with class ._zTable
<div class = "_zTable"> </ div>
Then in javascript, I have 1 variable (var div =)
which includes 1 div (class="folder") inside the div contains the table with id="exTable".
I want the table to be moved into ._zTable and not in the div class .folder.
Because I want the div .folder in the column folder.
var div = '<div class="folder"><span class="fname">Folder : '+name+'</span' +
'<table id="exTable' + currentFolderIndex + '" class="table table-bordered" cellspacing="0">' +
'<thead>' +
'<tr>' +
'<th style="border-color:rgb(221, 221, 221);"><input name="select_all" value="1" id="selectAll" type="checkbox" /></th>' +
'<th>Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'</tr>' +
'</thead>' +
'</table>' +
'</div>';
You will need to split your variable into two.
I notice your table is inside your .folder div. I presume that shouldn't be the case.
The variables are then:
var div = '<div class="folder"><span class="fname">Folder : '+name+'</span></div>'
var table = '<table id="exTable' + currentFolderIndex + '" class="table table-bordered" cellspacing="0">' +
'<thead>' +
'<tr>' +
'<th style="border-color:rgb(221, 221, 221);"><input name="select_all" value="1" id="selectAll" type="checkbox" /></th>' +
'<th>Name</th>' +
'<th>Type</th>' +
'<th>Size</th>' +
'<th>Date Created</th>' +
'</tr>' +
'</thead>' +
'</table>';
Then the code to put these in the right divs is:
document.getElementsByClassName("columnFolder-container")[0].innerHTML=div;
document.getElementsByClassName("_zTable")[0].innerHTML=table;
or with jquery:
$('.columnFolder-container').first().html(div);
$('._zTable').first().html(table);
Using Jquery :
`$(document).ready(function() {
$('#exTable').appendTo('.columnFolder-container');
});`
Here is my code in EJS which receives data in real time from my node server based on certain parameters.
<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">
<header>
<% include ../partials/header %>
</header>
<main>
<script src="/socket.io/socket.io.js"></script>
<table cellpadding="2" cellspacing="2" border="0" width="100%" align="center">
<thead>
<tr>
<th>Name</th>
<th>IsOnline</th>
<th>Location</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var socket = io();
socket.on('status', function(data){
var k = '<tbody>'
for(i = 0;i < data.length; i++){
k+= '<tr>';
k+= '<td>' + data[i].url + '</td>';
k+= '<td align="justify">' + data[i].name + '</td>';
k+= '<td align="justify" width="30%">' + data[i].status + '</td>';
k+= '<td align="justify" width="30%">' + data[i].loc + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
});
</script>
</main>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
This code works perfectly fine but,
I have 2 questions :
I can not figure out a clean way to change text color of value of IsOnline based on condition eg: if user is offline then text should be Offline in red color else green.
Also I've created this table using js and html as data variable was not available in EJS so is there some way to get this variable. I do not want to send data using res.render() or ejs.compile()
The following works for me:
for(i = 0;i < data.length; i++){
var color = data[i].status === "Offline" ? "red" : "green"; // If status is 'Offline', use red. If not use green
k+= '<tr>';
k+= '<td>' + data[i].url + '</td>';
k+= '<td align="justify">' + data[i].name + '</td>';
k+= '<td align="justify" width="30%" style="color: ' + color + '">' + data[i].status + '</td>';
k+= '<td align="justify" width="30%">' + data[i].loc + '</td>';
k+= '</tr>';
}
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 6 years ago.
I was wondering if it's possible to sort the final table content, before inserting it into the html, by the value of the paying column. The code generating the table is the following
function populateJobMarket() {
var tableContent = '';
$.getJSON('modalRoutes/jobmarket', function(data){
$.each(data, function() {
var cName = this.companyName;
$.each(this.hiring, function(){
tableContent += '<tr class=\'target_row\'>';
tableContent += '<td>' + cName + '</td>';
tableContent += '<td>' + this.paying + '</td>';
tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + this._id + '> Apply </button></td>';
tableContent += '</tr>';
});
});
$('#jobMarket_pp #joblist table tbody').html(tableContent); // Sort it before this step
});
}
HTML Code:
<div class="modal fade" id="jobMarket_pp" tabindex="-1" role="dialog" aria-labelledby="jobMarket_pp">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="jobMarket_content" Job Offers</h4> </div> <div class="modal-body"> <div class='jobMarketAlert'></div>
<div id="joblist">
<table>
<thead>
<th>Company Name</th>
<th>Salary</th>
<th>Work</th>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You'll first need to flatten the data:
var new_data = [];
$.each(data, function() {
var companyName = this.companyName;
$(this.hiring).each(function(index, hire){
hire.companyName = companyName;
new_data.push(hire);
});
});
Then sort the new flattened data by paying:
new_data.sort(function(a, b) {
return a.paying < b.paying;
});
Now iterate over the data:
$.each($(new_data), function(){
tableContent += '<tr class=\'target_row\'>';
tableContent += '<td>' + this.companyName + '</td>';
tableContent += '<td>' + this.paying + '</td>';
tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + this._id + '> Apply </button></td>';
tableContent += '</tr>'
});
I also recommend using, instead:
$(new_data).each(function(hire)) {
tableContent += '<tr class=\'target_row\'>';
tableContent += '<td>' + hire.companyName + '</td>';
tableContent += '<td>' + hire.paying + '</td>';
tableContent += '<td> <button type=\'button\' class=\'btn btn-warning job_apply\' id=' + hire._id + '> Apply </button></td>';
tableContent += '</tr>'
});
Using this is JavaScript often leads to headaches, as it doesn't behave like this in other languages.
I'm new to jQuery and JS. So I have this task to create tabel row using a dialog form. On every row the last cell must contain a button. My question is how can I add id for this specific button. I've tried selecting the button and adding .attr('id','delete'), but this changes the id of the button that opens the dialog.
So how can I add id only to the newly created button?
< script type = "text/javascript" >
function validateForm(form) {
var errors = [];
$(form.elements).each(function() {
var $this = $(this);
if (!$this.val()) {
var msg = $this.prev().html() + ' е задължително поле';
errors.push(msg);
}
});
return errors;
}
function saveForm(form) {
var nextNumber = $('table tr').length;
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button>' + '<span>' + 'Delete' + '</span>' + '</button>' + '</td>' +
'</tr>';
$('table').append(rowTpl);
}
$(function() {
$('#add-btn').button({
icons: {
primary: 'ui-icon-circle-plus'
}
}).on('click', function() {
$('#form-container').dialog('open')
});
$('#form-container').dialog({
autoOpen: false,
modal: true,
buttons: [{
text: 'Save',
click: function() {
var form = $(this).find('form').get(0);
var errors = validateForm(form);
if (errors.length) {
return alert(errors.join("\n"));
}
saveForm(form);
form.reset();
$(this).dialog('close');
}
}, {
text: 'Close',
click: function() {
$(this).find('form').get(0).reset();
$(this).dialog('close');
}
}]
});
})
$('#delete').button({});
$("#delete").click(function() {
$(this).parents('tr').first().remove();
});
< /script>
<style type="text/css"> table {
border-collapse: collapse;
}
th {
padding: 0.2em;
}
td {
margin: 0.2em;
padding: 0.2em;
text-align: center;
border: 1px solid grey;
}
.ui-widget-header,
.ui-widget-content {
padding: 0.8em;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
</style>
<div id="container" class="ui-widget">
<div class="ui-widget-header ui-helper-clearfix">
<h3 class="float-left">ALL CARS</h3>
<button class="float-right" id="add-btn">
<span>Add New Address</span>
</button>
</div>
<div class="ui-widget-content">
<table width="100%">
<tr>
<th>#</th>
<th>Марка</th>
<th>Модел</th>
<th>Година</th>
<th>Километри</th>
<th>Премахни</th>
</tr>
<tr>
<td>1</td>
<td>BMW</td>
<td>i8</td>
<td>2015</td>
<td>10 000</td>
<td>
<button class="float-center" id="delete">
<span>Delete</span>
</button>
</td>
</tr>
</table>
</div>
<div id="form-container" title="Add new car">
<form action="">
<div>
<label for="brand">Марка</label>
<input type="text" id="brand" />
</div>
<div>
<label for="model">Модел</label>
<input type="text" id="model" />
</div>
<div>
<label for="year">Година</label>
<input type="number" id="year" />
</div>
<div>
<label for="kms">Километри</label>
<input type="number" id="kms" />
</div>
</form>
</div>
</div>
Thank you!
Add id to the button in your rowTpl variable like following.
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button id="delete'+nextNumber+'">' + '<span>' + 'Delete' + '</span>' + '</button>' + '</td>' +
'</tr>';
It will add button id as delete1, delete2, delete3,......
ids are singular so you should not be setting the same id on multiple elements. Second the onclick you are adding with that id is not going to be attached to the button that you create after that code runs. Just like if the phone rings and you are not there, you will not answer it.
Use event delegation to detect what one was clicked and you can use closest to get access to the row the button resides in.
//attach the click handler to the table and listen for a click on a button
$("table").on("click", "button", function () {
var button = $(this); //The button that was clicked
var row = button.closest("tr"); //The row the button is in.
row.remove(); //delete the row
});
id must be unique in the entire document, so setting id to "delete" for all of these buttons is incorrect. You can set a class. When you are creating it, you could just create it as <button class='delete'>, and then use $(".delete") to find all buttons.
You can also set the action directly in the code:
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button onclick="$(this).closest(\'tr\').remove();">' + '<span>' + 'Delete' + '</span>' + '</button>' +
'</td>' +
'</tr>';
I try to use the jQuery Append method but its removing tags (tr, td) of my html code which I want to append. Why is it removing these and how can i force this method just to append and not to analyse my code?
Here is an example file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).on('click', '#button1', function () {
var htmlAppend = '';
htmlAppend = htmlAppend + '<input type="hidden" name="content0" value="' + 'hiddenvalues' + '"/>' + '<tr>' +
'<td>' + 'content1' + '</td>' +
'<td>' + 'content2' + '</td>' +
'<td>' + 'content3' + '</td>' +
'<td><input style="width: 300px" type="text" name="content4"/></td>' +
'</tr>';
$("#ScenarioCompetenceRatings").append(htmlAppend);
});
</script>
</head>
<body>
<button id="button1">Add Row</button>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th style="width: 300px">Column4</th>
</tr>
</thead>
<tbody id="ScenarioCompetenceRatings">
</tbody>
</table>
You are generating invalid markup. You should put the hidden input element in a td element. tbody element can only have tr children.
is this what you are trying to build? check on the fiddle i have created
http://jsfiddle.net/FWkd2/enter code here
to check my fiddle