I am currently using appendTo to add dynamic rows. What I want to happen is that if I will click one of the td (not including the remove button), It will open a bootstrap modal window and get the value of other td of its belonging row. here's the image.
Here's my code adding dynamically that I want to get the value of td and pass it to bootstrap modal.
function AddOrder(new_code, new_name, new_qtty, new_cost) {
var rows = "";
var code = new_code;
var name = new_name;
var cost = new_cost;
var qtty = new_qtty;
rows +=
'<tr>"' +
'<td class="item_code" data-toggle="modal" data-target="#mymodal">'+code+'</td>'+
'<td class="item_name" data-toggle="modal" data-target="#mymodal">'+name+'</td>'+
'<td class="item_qtty" data-toggle="modal" data-target="#mymodal">'+qtty+'</td>'+
'<td class="item_cost" data-toggle="modal" data-target="#mymodal">'+cost+'</td>'+
'<td>'+'<button class="btn remove-button">X</button>'+'</td>'+
'</tr>';
$(rows).appendTo("#dynamic_added tbody");
}
I tried putting putting onclick on td with data-toggle="modal" data-target="#mymodal" but only the modal is working not the function I'm using for example:
function GetData() {
$('.item_code').click(function(){
alert($(this).closest('tr').find('.item_code'));
});
}
I just solved my own problem just a bootstrap modal call is all I am missing.
I addded a class getdata that I will call to my javascript function
function AddOrder(new_code, new_name, new_qtty, new_cost) {
var rows = "";
var code = new_code;
var name = new_name;
var cost = new_cost;
var qtty = new_qtty;
rows +=
'<tr>"' +
'<td class="item_code getdata" onclick="GetData();">'+code+'</td>'+
'<td class="item_name getdata" onclick="GetData();">'+name+'</td>'+
'<td class="item_qtty getdata" onclick="GetData();">'+qtty+'</td>'+
'<td class="item_cost getdata" onclick="GetData();">'+cost+'</td>'+
'<td>'+'<button class="btn remove-button">X</button>'+'</td>'+
'</tr>';
$(rows).appendTo("#dynamic_added tbody");
}
If I will click anywhere to the td except the button It will pop up the modal and pass the current data of that row.
function GetData() {
$(document).on('click', '.getdata', function(){
$('#mymodal').modal();
var modal_code =$(this).closest('tr').find('.item_code').text();
var modal_name =$(this).closest('tr').find('.item_name').text();
var modal_qtty =$(this).closest('tr').find('.item_qtty').text();
var modal_cost =$(this).closest('tr').find('.item_cost').text();
var modal = $("#mymodal"); // this is the id of my modal
modal.find('.modal-body').text(modal_code + modal_name + modal_qtty + modal_cost);
});
}
Do you want something like this:
$('.item_code, .item_name, .item_qtty, .item_cost').click(function() {
$('.modal-body').html($(this).closest('tr').html());
$('#myModal').modal('show');
});
td {
border: 1px solid black;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="dynamic_added">
<tbody>
<tr>
<td class="item_code">code_1</td>
<td class="item_name">name_1</td>
<td class="item_qtty">qtt_1</td>
<td class="item_cost">cost_1</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
<tr>
<td class="item_code">code_2</td>
<td class="item_name">name_2</td>
<td class="item_qtty">qtt_2</td>
<td class="item_cost">cost_2</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
<tr>
<td class="item_code">code_3</td>
<td class="item_name">name_3</td>
<td class="item_qtty">qtt_3</td>
<td class="item_cost">cost_3</td>
<td>
<button class="btn remove-button">X</button>+</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Related
I am creating dynamic input rows to POST it into MySQL database
the first row is mandatory, so I created the FORM and Inputs via HTML for the first row
Then created a button and addEventListener function to append any additional row dynamically
Error
Actually, all nodes and children are working normally from the DOM side without any problem
When I submit the form, only the first static row is posted but any appended rows give Undefined array key
myJsFile.js
document.getElementById('add_row').addEventListener('click',function(e){
var my_tbody = document.querySelector('.my_tbodyClass');
var my_tr = document.createElement('tr');
my_tbody.appendChild(my_tr);
var my_div = document.createElement('div');
var my_td = document.createElement('td');
var my_input = document.createElement('INPUT');
my_input.setAttribute('type','number');
my_input.setAttribute('name','myRows[]');
my_tr.appendChild(my_td);
my_div.appendChild(my_input);
my_td.appendChild(my_div);
});
myphpFile.php
function execute_dynamicRow()
{
global $dbConnection;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submitedDynamicRows'])) {
$myRows = $_POST['myRows'];
$myRowsSerialized = serialize($myRows);
$stmt = mysqli_prepare($dbConnection, "INSERT INTO all_dynamic_rows(dynamic_rows) VALUES(?)");
$stmt_bind_param = mysqli_stmt_bind_param($stmt, 's', $myRowsSerialized);
$stmt_execute = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
if (!$stmt) {
die("Query Error " . mysqli_error($dbConnection));
}
}
}
myform.php
<?php myform(); ?>
<form method="post">
<table class="table table-flush">
<thead>
<tr>
<th class="text-uppercase text-secondary">Add You Number</th>
<th class="text-uppercase text-secondary">Add Row</th>
</tr>
</thead>
<tbody class="my_tbodyClass">
<tr>
<td>
<div>
<input type="number" name="myRows[]">
</div>
</td>
<td>
<button class="btn btn-icon btn-3" id="add_row" type="button">
<span class="btn-inner--text">Add New Row</span>
</button>
</td>
</tr>
</tbody>
</table>
<div class="input-group input-group-outline my-3">
<input type="submit" name="submitedDynamicRows" class="btn btn-info" value="Add Tax Slab">
</div>
</form>
I am trying to create a new table row every time the associated button is clicked. However, once I click the button and I go to select the row, it does not get highlighted. I have an append function that passes a <tr> to the html. My end goal is to have the the new row that was appended become clickable and can be selected.
Code:
<div class="col-md-3 left-pane">
<div class="row justify-content-md-center">
<button class="btn btn-sm btn-block eNew">New Tier</button>
</div>
<hr>
<table class="table table-sm table-hover tAdd">
<tbody>
<tr>
<td>IIS</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>SQL</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>Windows File Share</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
<tr>
<td>Etc</td>
<td><button class="btn btn-sm btnD">Delete</button></td>
</tr>
</tbody>
</table>
</div>
Javascript:
$(".eNew").on("click", function(event){
$(".tAdd tbody").append(
"<tr>" +
"<td>New Selector</td>" +
"<td><button class=\"btn btn-sm btnD\">Delete</button></td>" +
"</tr>"
);
$(".tAdd tr").click(function() {
$(".tAdd tr").removeAttr('class');
$(this).toggleClass("table-active");
});
Also, it works for the original <tr> that is in the html file but for some reason when I append a table row it does not work.
This is entirely due to the fact that dynamic content is not bound using the event handler you have declared:
$(".eNew").on("click", function(event){
Although this will bind to all .eNew elements when the code first runs, new elements will not be bound.
Instead, bind to the document and specify .eNew as a selector for the click event and it will work:
$(document).on("click", ".eNew", function(event){
Edit following OP comment about not working
Just to verify that your code should now look like this:
$(document).on("click", ".eNew", function(event){
$(".tAdd tbody").append(
"<tr>" +
"<td>New Selector</td>" +
"<td><button class=\"btn btn-sm btnD\">Delete</button></td>" +
"</tr>"
);
});
$(document).on("click", ".tAdd tr", function(event){
$(".tAdd tr").removeAttr('class');
$(this).toggleClass("table-active");
});
I created a website modul with PHP, MySQL, Bootstrap modal and Jquery. I have 4 checkboxes with datas. I store the datas in database. If the customer selects 2 checkboxes, a bootstrap modal appears with the relations between the 2 selection. It's actually works, but the modal shows the data several times.
In this case, computer1 is connected to computer3, which connected to computer4. So if I select computer1 and computer4, it shows the relations correctly, but several times:
$(document).ready(function() {
$('#checkBtn').click(function getElementRelation(element1, element2) {
var ele = document.getElementsByName("case");
var modal = document.getElementById("modaldata");
var hu = document.getElementsByName("hu");
var hu2 = document.getElementsByName("hu2");
if (modal.innerHTML === "") // if no relation is detected yet put start element
{
modal.innerHTML += element1;
}
//loop in data (this shows datas several times)
for (var i = 0; i < ele.length; i++) {
if (hu[i].innerHTML === element1) //if data = element 1 then put related element
{
modal.innerHTML += hu[i].innerHTML + "--->" + hu2[i].innerHTML + " ";
if (hu2[i].innerHTML !== element2) //if related element != end element call function to get relation between related element and end element
{
getElementRelation(hu2[i].innerHTML, element2);
}
}
}
var start = ""; //hold start element
var end = ""; //hold end element
for (var i = 0; i < ele.length; i++) {
if (ele[i].checked === true) {
if (start === "") {
start = hu[i].innerHTML; //set start element
} else {
end = hu[i].innerHTML; //set end element
}
}
}
checked = $("input[type=checkbox]:checked").length === 2;
if (!checked) {
alert("You must check 2 checkbox!");
return false;
} else {
getElementRelation(start, end);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Checkboxes -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Connect</th>
</tr>
</thead>
<tbody>
<tr>
<!-- Checkboxes -->
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer1">Computer1</p></td>
<td><p name="hu2" value="Computer3">Computer3</p></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer2">Computer2</p></td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer3">Computer3</p></td>
<td><p name="hu2" value="Computer4">Computer4</p></td>
</tr>
<tr>
<td><input type="checkbox" name="case"></td>
<td><p name="hu" value="Computer4">Computer4</p></td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Input button -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" id="checkBtn" value="View" data-toggle="modal" data-target="#myModal" class="btn btn-info">
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modaldata">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Select Computer1 and Computer3 and shows data several times
First, the paragraph tag does not have any attributes name or value. If you want to create new attributes, use HTML5 data-attributes.
To make the subsequent JS code easier, we will add these attributes to the input element. For example,
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
Second, your JS code was kind of confusing. My guess as to why you are getting duplicate results is because you are recursively calling getElementRelation().
I would simplify your code as below
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function () {
relations[this.dataset.name] = this.dataset.connect;
});
// when the getElementRelation() function is called normally, it is expected
// to have 2 arguments (element1 and element2);
// but as an event handler it will have 1 argument (Event object)
$('#checkBtn').click(function getElementRelation(e) {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name,
end = checkedBoxes[1].dataset.name;
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// you may want to delete the key to avoid any infinite loop in case
// delete relations[current];
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
One last thing, back in your HTML, remove data-toggle="modal" and data-target="#myModal" as we are opening the modal dynamically.
Demo
$(function() {
// cache jQuery objects that we will be re-using
var checkBoxes = $("input[name=case]");
var myModal = $("#myModal");
// get all relationships i.e. key = name, value = connect or null
var relations = {};
checkBoxes.each(function() {
relations[this.dataset.name] = this.dataset.connect;
});
$('#checkBtn').click(function() {
// get checked checkboxes
var checkedBoxes = checkBoxes.filter(":checked");
// validate first
if (checkedBoxes.length != 2) {
alert("You must check 2 checkbox!");
return false;
}
// build modal body
var html = '';
var current = checkedBoxes[0].dataset.name, // start with
end = checkedBoxes[1].dataset.name; // end with
while (current) {
html += current;
// check if it is connected
var next = relations[current];
// if it is not connected, stop
if (!next) {
html = 'Not related';
break;
}
// otherwise append HTML
html += ' -> ' + next + '<br>';
// if it is the end, stop
if (next == end) break;
// start over using connected one
current = next;
}
// update modal
myModal.find('.modal-body').html(html);
// open the modal dynamically once it is ready
myModal.modal('show');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Checkboxes -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Connect</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="case" data-name="Computer1" data-connect="Computer3"></td>
<td>Computer1</td>
<td>Computer3</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer2"></td>
<td>Computer2</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer3" data-connect="Computer4"></td>
<td>Computer3</td>
<td>Computer4</td>
</tr>
<tr>
<td><input type="checkbox" name="case" data-name="Computer4"></td>
<td>Computer4</td>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Input button -->
<div class="container">
<div class="row">
<div class="col-sm-12">
<input type="button" id="checkBtn" value="View" class="btn btn-info">
</div>
</div>
</div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body" id="modaldata">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
For unknown reasons to me I cannot display the last (sProductLink) value in this table :
<thead>
<tr>
<th>Id</th>
<th>Product Name</th>
<th>Brand</th>
<th>Price</th>
<th>Link</th>
</tr>
</thead>
I cannot see any reason for this issue. The html is the same as for the other elements.
Whne I look in the DOM I don't see the "Link" <td> at all, which means it is not added for some reason.
Here is the code for this. I will really appreciate if someone has a look at this.
$("#lblEditDeleteProducts").append('<tr><th class="idDom" scope="row">'
+sProductId+"<span data-i-user-id='"
+sProductId+"'</span>"
+"<button type='button' id='editBtn' class='btn btn-warning editBtn' data-toggle='modal' data-target='#myModal'>Edit</button>"
+ "<button id='deleteBtn' class='btn btn-danger deleteBtn'>Delete</button>"
+'</th><td class="nameDom">'
+sProductName+'</td><td class="brandDom">'
+sProductBrand+'</td><td class="priceDom">'
+sProductPrice+'</td><td class="linkDom">'
+sProductLink+'</td></tr>');
P.S. I'd also appreciate any tips on how can I do what I am doing here in an alternative(better) way. Without all the apostrophes and etc.
This part of your string:
"<span data-i-user-id='" +sProductId+"'</span>"
Should probably be:
"<span data-i-user-id='" +sProductId+"'></span>"
This is why building HTML via string concatenation is a colossal pain.
In the area where the skull 💀 is indicating, there's no greater than bracket > to close the inside of the <span>.
$("#lblEditDeleteProducts").append(
'<tr>
<th class="idDom" scope="row">'+sProductId+'
<span data-i-user-id="'+sProductId+'"💀</span>
<button type="button" id="editBtn" class="btn btn-warning editBtn" data-toggle="modal" data-target="#myModal">
Edit
</button>
<button id="deleteBtn" class="btn btn-danger deleteBtn">
Delete
</button>
</th>
<td class="nameDom">'+sProductName+'</td>
<td class="brandDom">'+sProductBrand+'</td>
<td class="priceDom">'+sProductPrice+'</td>
<td class="linkDom">'+sProductLink+'</td>
</tr>');
SNIPPET
var sProductId = 'sProd01';
var sProductName = 'sProExtreme';
var sProductBrand = 'sPro™';
var sProductPrice = 54.99;
var sProductLink = 'http://shop.spro.com';
$("#lblEditDeleteProducts").append('<tr><th class="idDom" scope="row">' + sProductId + '<span data-i-user-id="' + sProductId + '"></span><button type="button" id="editBtn" class="btn btn-warning editBtn" data-toggle="modal" data-target="#myModal">Edit</button><button id="deleteBtn" class="btn btn-danger deleteBtn">Delete</button></th><td class="nameDom">' + sProductName + '</td><td class="brandDom">' + sProductBrand + '</td><td class="priceDom">' + sProductPrice + '</td><td class="linkDom">' + sProductLink + "</td></tr>");
table {
border: 5px inset orange;
}
tr {
background: rgba(0, 0, 0, .7);
}
th {
border: 5px dashed green;
color: yellow;
}
td {
border: 2px inset blue;
color: cyan;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/g/fontawesome#4.6.3,bootstrap#3.3.7(css/bootstrap.min.css+css/bootstrap-theme.min.css)">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="lblEditDeleteProducts"></table>
I strongly suggest that you write the HTML that you're trying to append inside an editor, spaced out so you can see the structure properly and debug from there. You can minify it afterwards and test to ensure that it's in working order.
<tr>
<th class="idDom" scope="row">
+ sProductId +
<span data-i-user-id='"+sProductId+"'><!-- Closing '>' added (Thanks Matt) --></span>
<button type='button' id='editBtn' class='btn btn-warning editBtn' data-toggle='modal' data-target='#myModal'>
Edit
</button>
<button id='deleteBtn' class='btn btn-danger deleteBtn'>
Delete
</button>
</th>
<td class="nameDom">
+ sProductName +
</td>
<td class="brandDom">
+ sProductBrand +
</td>
<td class="priceDom">
+ sProductPrice +
</td>
<td class="linkDom">
+ sProductLink +
</td>
</tr>
Dont forget the "" marks around your HTML
I have a page that the user can dynamically add rows or tables to. I need to count the rows on a given table using jQuery to see if I just need to insert a row or a row and the header. Right now the count is just counting all rows on all tables. I am using jQuery 1.7.2 and the jquery templeter.
<div id="ClonePoint">
<button id="exitSection" class="closesection"><span>Close</span></button> <br /> <br />
<button class="btnEncode" id="buttonEncode">Encode</button>
<input id="encryptedTokenClone" />
<button class="btnDecode" id="buttonDecode">Decode</button>
<table class="tokenTable" cellpadding="3px">
<tbody class="tokenBody" >
</tbody>
</table>
<button id="addRow" class="addingRow">Add Row</button>
</div>
And the jQuery that is adding the rows
$('#BackgroundArea').on('click', '.addingRow', function () {
var selectedDiv = $(this).parent();
var selectedTable = $(selectedDiv).children('.tokenTable');
var rowCount = 0;
rowCount = $('.tokenTable .tokenBody').children('tr').length;
if (rowCount > 0) {
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
} else {
$("#TableHeader")
.tmpl()
.appendTo(selectedTable);
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
}
});
The html for the insert is
<script id="TableHeader" type="text/html">
<tr id="TableHead">
<th width="55px">Delete Row</th>
<th align="right"> Key </th>
<th align="left"> Value </th>
</tr>
</script>
<script id="tokenAddRowTemplate" type="text/html">
<tr id="tokenRow">
<td class="deleteRow" id="tokenCell">
<button class="deleteRow">
<span>delete row</span>
</button>
</td>
<td class="keyValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
<td class="valueValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
</tr>
</script>
This should give tr count in your table.
$("#yourTableId tr").length
Is this what your are looking for ?
If each table is followed by its own "Add Row" button:
var $table = $(this).prev(),
rowCount = $table.find('.tokenBody').children('tr').length;
if (rowCount > 0) {
...
This assumes the "Add Row" button immediately follows the table.
To make the code less brittle, you could consider using a container element, like this:
<div class="tokenTableContainer">
<table class="tokenTable">
...
<table>
<button class="addingRow">...</button>
</div>
Then you can do this:
$('.addingRow').click(function() {
var $table = $(this).closest('.tokenTableContainer').find('.tokenTable');
...
});