I am using two fields from the table. I can get first-row value, then I added second-row value but can't get second-row value. I need if I add multiple rows, I can get all value using JSON .can you please solve these issues.
HTML:
<button class="add">Add</button>
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button class="send">Send</button>
Script:
$("document").ready(function(){
$(".add").click(function(){
var td_add="<tr><td><input type='text' id='name' class='name'></td><td><input type='text' id='age'></td></tr>";
$("tbody").append(td_add);
});
$(".send").click(function(){
var name=document.getElementById("name").value;
var age=document.getElementById("age").value;
var obj={
name:name,
age:age
};
alert(JSON.stringify(obj));
});
});
Output: i can get single row value.
{"name":"aravind","age":"42"}
i have fixed your code please check it.
$("document").ready(function() {
$(".add").click(function() {
var td_add = "<tr><td><input type='text' name='aa' id='name' class='name'></td><td><input type='text' name='bb' id='age'></td></tr>";
$("tbody").append(td_add);
});
$(".send").click(function() {
var asa = [];
$("input[name*='aa']").each(function(key, item) {
if (!asa[key]) asa[key] = {};
asa[key].calvalue = item.value;
});
$("input[name*='bb']").each(function(key, item) {
if (!asa[key]) asa[key] = {};
asa[key].calvalue2 = item.value;
});
alert(JSON.stringify(asa));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="add">Add</button>
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button class="send">Send</button>
Reason:
You will always get the value of the first row because on dynamically adding rows, you are keeping same id and name for all input elements.
Solution:
Use class instead of id to get the element's value in a loop.
e.g
var names = document.getElementsByClassName("name");
for(var i = 0; i < names.length; i++)
{
names[i].value
}
Or, use this one, creating an array of objects in the form of
dat = [
{
"name": "Charlie Brown",
"age": "13"
},
{
"name": "Peppermint Patty",
"age": "11"
}
]
var tr_add="<tr><td><input type='text' name='name'></td><td><input type='text' name='age'></td><td><select name='gender'><option>female</option><option>male</option></select></td><th><input type='text' name='shoesize'></th></tr>";
$(function(){
$(".add").click(function(){ $("tbody").append(tr_add); });
$(".send").click(function(){
var dat=$("#myform").serializeArray().reduce(function(a,v){
if (v.name=='name') a.push({name:v.value}); // add new object to array
else a[a.length-1][v.name]=v.value; // add attribute to existing object
return a;
},[])
console.log(dat); });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button class="add">Add</button><form id="myform">
<table class="orders-detail table table-striped table-bordered row-border hover" width="100%">
<thead><tr><th>Name</th><th>Age</th><th> gender</th><th>shoe size</th></tr></thead>
<tbody></tbody>
</table></form>
<button class="send">Send</button>
The data can be extended without having to change anything in the script. It will collect all the data according to the name attribute of the input element.
The only "fixed" point in this script is that the first input field must be the one with name="name". This will trigger the creation of a new object in the dat-array.
Related
I need to make a counter using JavaScript/JQuery with clone method in the second column like for example the first row 1 and when I click on add button it automatically display number 2. I am using clone method in JavaScript/JQuery and I don't know how to add this. This is my full code:
var cloned = $('#myTable tr:last').clone();
$(".add-row").click(function(e) {
e.preventDefault();
cloned.clone().appendTo('#myTable');
});
$('#myTable').on('click', ".delete-row", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover table-striped table-sm" id="myTable">
<thead>
<th></th>
<th>#</th>
<th>test1</th>
<th>test2</th>
<th>test3</th>
<th>test4</th>
<th>test5</th>
</thead>
<tbody>
<tr>
<td>
delete
</td>
<td>
<!-- Counter here -->
</td>
</tr>
</tbody>
</table>
add
Consider the following.
$(function() {
function cloneLastRow(table) {
var row = $("tr:last", table);
var clone = row.clone();
$("td:eq(1)", clone).html($("tbody tr", table).length + 1);
clone.appendTo($("tbody", table));
}
function renumberTable(table) {
var count = 1;
$("tbody tr", table).each(function(i, row) {
$("td:eq(1)", row).html(count++);
});
}
$(".add-row").click(function() {
cloneLastRow($("#myTable"));
});
$("#myTable tbody").on("click", ".delete-row", function() {
var row = $(this).closest("tr");
if (confirm("Are you sure you want to delete the Row?")) {
row.fadeOut("slow", function() {
row.remove();
renumberTable($("#myTable"));
});
}
})
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover table-striped table-sm" id="myTable">
<thead>
<th> </th>
<th>#</th>
<th>test1</th>
<th>test2</th>
<th>test3</th>
<th>test4</th>
<th>test5</th>
</thead>
<tbody>
<tr>
<td>
delete
</td>
<td>
1
</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
add
There is no need for a Counter when you can just request the current length of a selector. For example, you can get the length of all the Rows in the Table Body. Initially, that is 1. The next one would be 2.
Now if the table has a unique start, lets say 20, then you would want to get that String value, cast it as an Integer, and increment that value.
$("td:eq(1)", clone).html(parseInt($("td:eq(1)", row).text()) + 1);
This would result in 21.
Update
Based on your comment, when you delete a row, you want the numbers to remain continuous. This means you need to redraw all or at least all further numbers.
function renumberTable(table){
var count = 1;
$("tbody tr", table).each(function(i, row){
$("td:eq(1)", row).html(count++);
});
}
You would then run this function directly after a Row was removed.
He want to do an input box with a Filter Table options.
My input box is:
<input class="form-control" id="myInput" type="text" placeholder="Search..">
and this code to generate a table:
$data = '<table class="table table-bordered table-striped">
<tr>
<th>No.</th>
<th>Status</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Update</th>
<th>Delete</th>
</tr>';
$query = "SELECT * FROM users";
and my js is:
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
is it necessary to use a tbody or anything else to do a Filter Table?
or not’s possible to do an exception for the first ?
very thanks!
yes, is possible to do an exception for the first. Try something like:
$('table tr:gt(1)').filter...
(Your header has 1 row, so it will work)
I do it!
Finally with this code:
$(function(){
$("#myInput").on("keyup", function() {
var $value = $(this).val().toLowerCase();
$("#myTable tr:gt(0)").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf($value) > -1)
});
});
});
I have some HTML that looks as follows:
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
#foreach (var item in Model.AccommodationList)
{
<tr>
<td class="accommodationName">
#Html.ActionLink(item.AccommodationName, "ViewHomePage", "AccommodationHomepage", new {accommodationId = item.AccommodationId}, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.FormattedAddress)
</td>
<td>
<Deleted for brevity>
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalReviews)
</td>
<td class="latitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td class="longitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Longitude)
</td>
</tr>
}
</tbody>
</table>
I am trying to get the value of the accommodation name, latitude and longitude in each row with the following jQuery:
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
});
}
However I must be doing something incorrectly because I'm not able to get any values.
Use javascript table.rows function and textContent property to get the inner text of the cell like you can do something like below:
for(var i = 1, row; row = table.rows[i]; i++)
{
var col1 = row.cells[0].textContent;
var col2 = row.cells[1].textContent;
} var col3 = row.cells[2].textContent;
Don't use innerText it is much slower than textContent and also doesn't work in firefox.
I wrote up a fiddle and modified some of your code so I could put text in your cells, I am wondering if this will help you? If not could you write up a small fiddle and I can provide some more assistance.
https://jsfiddle.net/y3llowjack3t/8cL94hgq/
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
alert(latitude);
});
You are getting the data correctly but, you don't seem to do anything with the values you obtain from the table. And, after .each(), you will not have access to even the values from the last row since you're using local variables. You can create an array that has all the data.
Give this a try:
var locations = $('#resultsTable tbody tr').map(function() {
var location = {};
location.latitude = $(this).find(".latitudeCell").html();
location.longitude = $(this).find(".longitudeCell").html();
location.accommodationName = $(this).find(".accommodationName").html();
return location;
}).get();
console.log( locations );
//OUTPUT: [{"latitude": "<val>","longitude": "<val>", "accommodationName": "<val>"},{.....},....]
Your code works for me:
example
In the code you paste you put a } more, try to check if there's some issues with brakets.
Here is a working example. In your example, I did not see how you were calling your function. I enclosed your function in $().ready() so that it is called when the DOM is ready. You will want to call your function any time the tan;e content changes.
$().ready(function() {
$('div#cellValues').empty();
$('div#cellValues').append('<ul></ul>');
$('#resultsTable tbody tr').each(function(index) {
var latitude = $(this).find('.latitudeCell').html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
$('div#cellValues ul').append('<li>' + accommodationName + ': [' + latitude + ',' + longitude + ']</li>');
});
});
#cellValues {
border: 1px solid red;
}
#cellValues::before {
content: "Cell Values:";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cellValues"></div>
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
<tr>
<td class="accommodationName">accomidationName1</td>
<td>FormattedAddress1</td>
<td></td>
<td>TotalReviews1</td>
<td class="latitudeCell" style="display: none;">Latitude1</td>
<td class="longitudeCell" style="display: none;">Longitude1</td>
</tr>
<tr>
<td class="accommodationName">accomidationName2</td>
<td>FormattedAddress2</td>
<td></td>
<td>TotalReviews2</td>
<td class="latitudeCell" style="display: none;">Latitude2</td>
<td class="longitudeCell" style="display: none;">Longitude2</td>
</tr>
<tr>
<td class="accommodationName">accomidationName3</td>
<td>FormattedAddress3</td>
<td></td>
<td>TotalReviews3</td>
<td class="latitudeCell" style="display: none;">Latitude3</td>
<td class="longitudeCell" style="display: none;">Longitude3</td>
</tr>
</tbody>
</table>
I have write a code and getting the values via jQuery and Ajax using the following code, the data comes fine but i could not populate the rows in my table. the looping is not work.
This is my table code in html
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Hospital Details</th>
<th>Requested Product</th>
<th>Units</th>
<th>Patient Details</th>
<th>Interval</th>
<th>Requester</th>
</tr>
</thead>
<tbody id="result">
</tbody>
</table>
</div>
This is my ajax script
<script>
$.get("./../incomingRequestList.php", function(data, status){
var obj = jQuery.parseJSON(data);
for($i=0; $i<obj.length; $i++){
$response += "<tr><td>1</td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
}
$('#result').html($response);
});
</script>
How can i overcome this issue. I am unable to find out why its wrong.
The correct way to do it is:
<script>
$.get("./../incomingRequestList.php", function(data, status){
var obj = jQuery.parseJSON(data);
var response = '';
for(i=0; i<obj.length; i++){
response += "<tr><td>"+obj.number+"</td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
}
$('#result').html(response);
});
</script>
I want to get row index and text box values when the table price text box value changes. At the moment I'm getting some undefined value.
HTML
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control product">
</td>
<td>
<input type="text" oninput="javascript:GetValue(this);" class="form-control price">
</td>
</tr>
</tbody>
</table>
JavaScript
function GetValue(oTextBox) {
var price = oTextBox.value;
var product = oTextBox.parent().prev().innerHTML.value;
var rowindex = oTextBox.closest('tr').index();
}
I get this error:
TypeError: oTextBox.parent is not a function
var product = oTextBox.parent().prev().innerHTML.value;
You need to wrap oTextBox in $ in order to use jQuery methods. That's because oTextBox ... or ... this is a DOM element and not a jQuery object. Thus:
var product = oTextBox.parent().prev().innerHTML.value;
Should be:
var product = $(oTextBox).parent().prev().find('input').val();
And:
var rowindex = oTextBox.closest('tr').index();
Should be:
var rowindex = $(oTextBox).closest('tr').index();
SUGGESTION
I would encourage you to not use inline JS:
<input type="text" class="form-control price">
Then your jQuery would be:
$(function() {
$('input.price').on('input', function() {
var price = this.value;
var product = $(this).parent().prev().find('input').val();
var rowindex = $(this).closest('tr').index();
//....
});
});
Replace oTextBox in the function by $(oTextBox) and then you can use html() instead of innerHTML, like so
$(oTextBox).parent().prev().html()