jQuery Append removing tags - javascript

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

Related

How to reload view after AJAX POST

Being new to AJAX I have encountered this problem and have had no luck resolving it. I want my table to be refreshed after an ajax post to review an object, everything I've tried has been futile.
Assume the ajax response is a JSON result, to avoid posting my OnPost() code.
I send the Id of the product using ajax and then use that Id to remove the product
I then call the same method OnGet() uses to populate the tables which returns the updated list. In chrome debug tools I see the response successfully returns with the updated list. I just don't know how to get it across back to my list. Thanks in advance guys.
#Html.AntiForgeryToken()
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ShoppingBagItems)
{
<tr>
<td>
#item.Product.Name
</td>
<td>
#item.Price.ToString("C")
</td>
<td>
<input value="#item.Quantity" size="1" maxlength="1" class="text-center" />
</td>
<td>
<button onclick="remove(#item.Product.Id.ToString())" class="close">
<span aria-hidden="true">×</span>
</button>
</td>
</tr>
}
</tbody>
</table>
<script>
function remove(id) {
$.ajax({
type: 'POST',
url: 'ShoppingBag?handler=Delete',
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: ''+id+'',
sucess: function (response) {
append_json(response);
}
});
}
function append_json(data){
var table = document.getElementById('shoppingBag');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
</script>
In Ajax success method after this append_json(response);add below code to refresh the table
$("#shoppingBag").load(window.location + " #shoppingBag");
change:
var table = document.getElementById('shoppingBag');
to:
var table = $('#shoppingBag tbody');
AND
change:
table.appendChild(tr);
to:
table.append(tr);
you are appending your data to main <table> if you inspect your table you can see the appended html.but you need to append data in body of table
for this you can use $("#shoppingBag tbody").append(tr);
or you can add id to <body> like <tbody id="myTestTableBody"> and use this in to your JavaScript
function append_json(data){
var table = document.getElementById('myTestTableBody');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
I have added a sample code that how you can append data to existing table
var page=1;
function AddData() {
$.ajax({
url: "https://reqres.in/api/users?page="+page,
type: "GET",
success: function(response){
append_json(response.data);
}
});
page++;
}
function append_json(data){
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.first_name +
'</td>' +
'<td>' +
object.last_name +
'</td>' +
'<td>' +
'<img src ='+object.avatar +' width="50px" height="50px" />'+
'</td>';
$("#shoppingBag tbody").append(tr);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Add Data" onclick="AddData()">
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

How to get checked checkbox table value in jquery

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,....)
});

Why my css display Irregular?

My HTML Code is like this :
...
<button class="save bookbtn mt1">More</button>
...
<div class="cruisedropd">
<div id="loading" class="loading"></div>
</div>
...
My Javascript Code is like this
...
$('.save').click(function () {
...
success: function (response) {
...
var elem = $parent.find('.loading').empty();
elem.append('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<response.SearchAvailResponse.Hotel.length; i++){ //make sure to use var
elem.append('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td>Cancel Policy</td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>'); //add the new content
}
elem.append('</tbody>\
</table>')
...
}
...
}
...
The View is like this : http://imgur.com/1OIVGGU
Why my css display irregular?
Any solution to solve my problem?
Thank you very much
The short answer is that you can not build a table in that way.
Your first snippet of code appends the table headers. Then DOM automatically adds closing table tag.
Your next snippet of code runs a loop to append rows. However, the table was already created in the previous step.
So you end up with 2 tables in the DOM which don't align.
Suggest building the table as a string and then appending that string to the div so that the DOM builds a single table.
UPDATE:
This code, in response to OP comment, demonstrates how to make the original code work with just 3 very minor changes. The table is first built as a string. The string is then appended to the innerHTML of the container. Doing it this way prevents the DOM from prematurely adding a closing tag to the table element, as was the case in the original code.
And now the table header and rows align, which was the stated problem.
Click the "Run code snippet" button to see it work.
function success() {
var html =('<table class="table">\
<tbody>\
<tr>\
<th>Status</th>\
<th>Room Grade</th>\
<th>Meal</th>\
<th>Per Room.Night</th>\
<th>Cancel Policy</th>\
<th>Book It</th>\
</tr>')
for(var i=0; i<10; i++){
html += ('<tr>\
<td>' + Status + '</td>\
<td>' + RmGrade + '</td>\
<td>' + Meal + '</td>\
<td>' + Currency + ' ' + TotalRate + '</td>\
<td>Cancel Policy</td>\
<td>\
<form action="details.html">\
<button class="bookbtn mt1" type="submit">Book</button>\
</form>\
</td>\
</tr>');
}
html += ('</tbody>\
</table>');
$('#container').html( html );
}
// test data
var Status="OK", RmGrade=5, Meal="Yes", Currency="Euro", TotalRate="100";
success();
td,th {padding:2px; border:1px gray solid;}
th {background-color: peru; }
table {border-collapse: collapse;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="container"></div>
Do you mean that the table content is not aligned properly? Verify your CSS that there is no width property on your TD element.
HTML:
<table>
<tr>
<th>Test1</th>
<th>Test2</th>
<th>Test3</th>
</tr>
<tr>
<td>Wat</td>
<td>Wat2</td>
<td>Wat3</td>
</tr>
<tr>
<td>Foo</td>
<td>Foo2</td>
<td>Foo3</td>
</tr>
</table>
CSS:
table {
width: 100%;
}
th, td {
text-align: left;
}
Fiddle: https://jsfiddle.net/vup7vz1k/1/

Function does not seem to be executing on click

Well... the tittle says it. Here, I leave you the link.
I lost nearly 4 hours trying to make it work!
I want to add rows to the table, when I click the button. But it does not seem to do anything at all.
http://jsfiddle.net/QqMsX/24/
<table class="table table-bordered">
<thead>
<tr>
<th>Relation</th>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
</tr>
</thead>
<tbody id = 'FamilyTable'>
</tbody>
</table>
<button onclick ="AddRow()" type="button" class="btn btn-primary">Add</button>
And the JavaScript Code.
function AddRow()
{
var Row = '<tr>'.
'<td>Data</td>'.
'<td>Data</td>'.
'<td>Data</td>'.
'<td>Data</td>'.
'<td>Data</td>'.
'<td>Data</td>'.
'</tr>';
$(Row).appendTo("#FamilyTable");
}
The string concatenation character in Javascript is +, not .. Also note that your original fiddle did not include jQuery. Try this:
function AddRow() {
var row = '<tr>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'</tr>';
$(row).appendTo("#FamilyTable");
}
Updated fiddle
A better alternative would be to attach your events using Javascript to avoid the outdated on* attributes. Something like this:
<button type="button" class="btn btn-primary">Add</button>
$(function() {
$('button').click(function() {
var row = '<tr>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'<td>Data</td>' +
'</tr>';
$(row).appendTo("#FamilyTable");
});
});
Example fiddle

How to insert a new element after an element by using the selector

I just want to ask how can I add a new element after a specific element after the button is clicked.
Here's my sample code:
<table id="table-1" border="1" style="border: 1px solid #ccc; width: 100%">
<thead>
<tr>
<td>TITLE</td>
<td>TITLE</td>
<td>TITLE</td>
<td>TITLE</td>
<td>TITLE</td>
</tr>
</thead>
<tbody id="no-row">
<td colspan="5">no content</td>
</tbody>
<tfoot>
<tr>
<td colspan="5">footer</td>
</tr>
</tfoot>
</table>
<button id="add-row">Add Row</button>
I have this simple jquery:
$('#add-row').on('click', function(){
var counter = 1;
var add_row = '<tbody>';
add_row += '<tr>';
add_row += ' <td>' + counter + '</td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += '</tr>';
add_row += '</tbody>';
$('#table-1 #no-row').remove();
$('#table-1 thead').append(add_row);
counter++;
});
But it just appending it inside the thead.
Here's the fiddle:
http://jsfiddle.net/rochellecanale/gov88ucm/1/
append() inserts the specified content within the selected element. To insert it after the element use the after() method instead:
$('#table-1 thead').after(add_row);
Updated fiddle
how can i display the newest added row to the bottom?
You can select the tfoot and use before():
$('#table-1 tfoot').before(add_row);
Example fiddle
Try this...
Change $('#table-1 thead').append(add_row); to $('#table-1').append(add_row);
var counter = 1;
$('#add-row').on('click', function(){
var add_row = '<tbody>';
add_row += '<tr>';
add_row += ' <td>' + counter + '</td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += ' <td></td>';
add_row += '</tr>';
add_row += '</tbody>';
$('#table-1 #no-row').remove();
$('#table-1').append(add_row);
counter++;
});
You need to use the after keyword. The after keyword Insert content, specified by the parameter, after each element in the set of matched elements.
$('#table-1 thead').after(add_row);
Your <tbody> is missing a <tr>
<tbody>
<tr id="no-row">
<td colspan="5">no content</td>
</tr>
</tbody>
change your add_row to remove tbody then append directly to the tbody
$('#table-1 #no-row').remove();
$('#table-1>tbody').append(add_row)
this way, your append function is re-usable as you're currently re-adding the tbody every time.
To answer the question specifically, you can add the ID to tr as above, remove tbody from add_row and add after the no-row:
$('#table-1 #no-row').hide();
$('#table-1 #no-row').after(add_row)

Categories