I've Add the event click to my dynamic table but it doesnt work.
$("#gridVille").append('<table id="idTableVille" class="table table-striped table-hover">');
$("#idTableVille").append('<thead>');
$("#idTableVille thead").append('<tr><th>Code commune</th><th>Libellé</th></tr>');
$("#idTableVille").append('</thead>');
$("#idTableVille").append('<tbody>');
for (i = 0; i < liste.length; i++) {
$("#idTableVille tbody").append('<tr id="' +liste[i].id+ '">');
$('#idTableVille tbody').append('<td scope="row" class="idCommune">' + liste[i].id+ '</td>');
$('#idTableVille tbody').append('<td class="libelleCommune">' + liste[i].libelle+ '</td>');
$("#idTableVille tbody").append('</tr>');
}
$("#idTableVille").append('</tbody>');
$("#gridVille").append('</table>');
$('#idTableVille tr').click(function () {
var id = $(this).find('td:eq(0)').text();
var libelle = $(this).find('td:eq(1)').text();
alert(id + ' ' + libelle);
});
this code is added after populating the table.
The scenario is :
I Open the modal (bootstrap modal)
I populate the table
I click to any row of table for getting the values of columns
You are appending the <tr> element to the <tbody> and then also appending every <td> to the <tbody> instead of the newly generated row, so instead of a regular table structure:
<table>
<tbody>
<tr id="something">
<td>Something</td>
<td>Hello!</td>
</tr>
</tbody>
</table>
You are getting this:
<table>
<tbody>
<tr id="something"></tr>
<td>Something</td>
<td>Hello!</td>
</tbody>
</table>
If you change the code inside the for loop it should get fixed:
for (i = 0; i < liste.length; i++) {
$("#idTableVille tbody").append('<tr id="' +liste[i].id+ '">');
$('#idTableVille tbody tr#' + liste[i].id).append('<td scope="row" class="idCommune">' + liste[i].id+ '</td>');
$('#idTableVille tbody tr#' + liste[i].id).append('<td class="libelleCommune">' + liste[i].libelle+ '</td>');
}
As you can see, I'm appending the elements to the newly created row, using the id to select it.
You can see it working here:
https://jsbin.com/yojajisuca/edit?html,js,output
Related
I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/
I'm trying to do dynamic table with bootstrap but I can't deduce why it's not working. There's a HTML part:
<div class="container">
<button onclick="CreateTable()">Extend</button>
<table class="table">
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John Doe</td>
<td>Country1</td>
</tr>
<tr>
<td>2</td>
<td>Mary Moe</td>
<td>Country2</td>
</tr>
<tr>
<td>3</td>
<td>Jack Dooley</td>
<td>Country3</td>
</tr>
<p id="id_tabela"></p>
</tbody>
</table>
</div>
and there's javascript:
function CreateTable() {
var employee = new Array();
employee.push([4, "Billie Jean", "Country4"]);
employee.push([5, "Harish Kumar", "Country5"]);
employee.push([6, "Pankaj Mohan", "Country6"]);
employee.push([7, "Nitin Srivastav", "Country7"]);
employee.push([8, "Ramchandra Verma", "Country8"]);
var tablecontents = "";
for (var i = 0; i < employee.length; i++) {
tablecontents += "<tr>";
for (var j = 0; j < employee[i].length; j++) {
tablecontents += "<td>" + employee[i][j] + "</td>";
}
tablecontents += "</tr>";
}
document.getElementById("id_tabela").innerHTML = tablecontents;
}
So I want to extend the table and I can't figure out why it's not working.
You are loading the data inside the paragraph, which is not what you want to do. Also the paragraph shouldn't be there. You can add an id to tbody and then just extend its innerHTML like so: https://jsfiddle.net/14pt76wp/.
Why are you using native functions? bootstrap has jQuery included. You could do something like:
$('table tbody').append(tablecontents);
Another trick:
Iterate over the array and do employee[i] = '<td>' + employee[i].join('</td><td>') + '</td>';
tablecontents = '<tr>' + employee.join('</tr><tr>') + '</tr>';
In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});
I am new to jQuery. I have table contents displayed by jQuery using Bootstrap. I want to hyperlink for each value to be link to url. I don't know how to embed jQuery inside another jQuery to make this happen. I used [href= "www.google.com/" + run_accession> run_accession ] but this doesn't take run_accession parameter.
<table id="resultsTable" class="table table-hover">
<thead>
<tr><th><input type="checkbox" id="selectAll" checked="true" \></th>
<th class="sortable" sort-target="run_accession">Run</th>
<th class="sortable" sort-target="experiment_accession">Experiment</th>
</thead>
<tbody id="results_display">
{% for sra in sra_page %}
<tr><td><input class="srasCb" checked="true" type="checkbox" name="sras" value="{{ sra.run_accession}}"\></td>
<td>{{ sra.run_accession }}</td>
<td>{{ sra.experiment_accession }}</td>
</tr>
{% endfor %}
<script>
var propagate_table = function(data) {
$('#results_display').empty();
for (i = 0; i < data.length; i++) {
$('#results_display').append('<tr><td> <input class = "srasCb"'
+ checkboxSelection +' type="checkbox" name="sras" value="' + run_accession +'"\></td><td>'
// I want to make <td> as link to url as: www.example.com/data[i].fields.run_accession
+ data[i].fields.run_accession; + '</td><td>'
+ data[i].fields.experiment_accession + '</td><td>'
);
}
}
</script>
Would highly appreciate your suggestions.
To make <td> behave as a link you can create <td> elements using jQuery constructor inside your for loop and attach click event listeners to them, something like this:
var container = $('#results_display');
for (i = 0; i < data.length; i++) {
// create elements using jquery
var tr = $('<tr/>');
var td1 = $('<td/>', {
text: 'cell 1'
});
var td2 = $('<td/>', {
text: 'cell 2'
});
// add click event listener to td1
td1.click(function () {
// go to url on click
window.location.href = "http://google.com";
});
// append elements to container
td1.appendTo(tr);
td2.appendTo(tr);
tr.appendTo(container);
}
Here is jQuery documentation about creating elements http://api.jquery.com/jquery/#jQuery-html-ownerDocument
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