Actually I am retrieving some data from database through ajax and on retrieval of data i made some dynamic element in html using javascript. I made dynamic row in a container and in that row i making a dynamic div whose class is "col-md-4" it means there can be atleast 3 divs in a dynamic .... Now no. of divs whose class is col-md-4 depends upon the rows retrieved from database it means everytime when data is retrieved there will be a new row in which a new div will form with only div col-md-4. Now i want there should be 3 divs of class-md-4 should be created then new should be created
$.ajax({
url: '../php/admin/upcoming_match.php',
type: 'post',
data: {},
success: function(response) {
var n=1;
var data = JSON.parse(response);
if(data!=''){
$.each(data, function(i, item) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class","row");
row1.setAttribute("id","row"+n);
parent.appendChild(row1);
var child=document.getElementbyId('row'+n);
var crow1= document.createElement("div");
crow1.setAttribute("class","col-md-4");
crow1.setAttribute("id",data[i].id);
row1.appendChild(crow1);
n++;
return n;
});
}
}
});
In this code the new dynamic will have only one child div ... i want should have atleast 3 child divs. For e.g, if we retrieved 4 rows from database then there should a new dynamic row which should have 3 child divs that contain the data of 3 rows then there should be a new row which should 4th child div row but in my present if i retrieve 4 rows then 4 news row class are formed which contain a child div that contain the data of each row retrieved from database
What about something like this ?
It would be easier to have demo data. You can upvote or accept if you like that.
var ajax = prompt('Confirm demo or paste AJAX data', '[ {"id":1}, {"id":2}, {"id":3}, {"id":4}, {"id":5}, {"id":6}, {"id":7}, {"id":8}, {"id":9}, {"id":"A"} ]');
display(ajax);
function display(response) {
var n=1;
var data = JSON.parse(response);
if(data.length) {
for(var i=0;i<data.length;i++) {
var parent= document.getElementsByClassName('carousel')[0];
var row1= document.createElement("div");
row1.setAttribute("class", "row");
row1.setAttribute("id", "row"+n);
parent.appendChild(row1);
var crow1;
for(var j=0;j<3 && i+j < data.length;j++) {
crow1 = document.createElement("div");
crow1.setAttribute("class", "col-md-4");
crow1.setAttribute("id", data[i+j].id);
crow1.innerText = "data" + (i+j) + " id" + data[i+j].id;
row1.appendChild(crow1);
}
i += 3-1;
n++;
}
}
}
DIV.col-md-4 {
display: inline;
background-color: #FF0080;
margin: 5px;
}
.row {
display: block;
background-color: #80E080;
padding: 3px;
}
<div class="carousel">
</div>
Related
I want to get all values from qty column, and in the qty column I was put contenteditable="true" here is pic of my table
var ids_selected = []
var sendData = function() {
$.post(BASE_URL+'/part_request/request_insert', {
data: { ids : ids_selected, request_to :
$('#request_to').val()}
}, function(response) {
console.log(response);
});
}
`sendData();
I want to put qty into array here pic of my array
Thank you
I have been struggling with this for days, I have a function that takes in an object and loops through it creating rows with display columns in it (bootstrap), so I am using jQuery in order to select an id with a value from the object itself and appending to it, but for some reason the id selector that contains the variable is not seen and does not append to the div with the id?
function add_to_page(product) {
//this is the main row that will contain the columns
var rows = $('<div class="row" ></div>');
for (var category in products) {
for (var i = 0; i < products[category].length; i++) {
rows.append($("<div id='" +products[category][i].id +"'></div>").html($('<img>').attr('src', products[category][i].img)));
//the below code is never executed it only creates the image and stops appending after that
$('#' + products[category][i].id).append($('<div class=name>').text(products[category][i].name));
$('#' + products[category][i].id).append($('<div class=category>').text(products[category][i].category));
$('#' + products[category][i].id).append($('<div class=price>').text('Price: ' + products[category][i].price + 'L.E'));
$('#' + products[category][i].id).addClass('col-md-3');
//the below code is to create a new row after filling each row with 4 display columns
if ( i % 3 == 0 && i != 0 ) {
$('#content').append(rows.clone(true));
rows = $('<div class="row"></div>');
}
}
}
}
here is the html i am trying to append to:
<div class="container full-width">
<div id="content"></div>
</div>
i am calling the function normally , no error in the console
add_to_page(products);
You cannot use a selector to find an element you have not yet added to the document (unless you use the second argument of $(selector, context)). But for your purposes, you can just use the fact that the append method can accept more than one argument.
With some other changes to make your code more jQuery-like, you get this:
function add_to_page(products) {
//this is the main row that will contain the columns
var rows = $('<div>').addClass("row");
for (var category in products) {
for (var item of products[category]) {
rows.append(
$("<div>").attr("id", item.id).addClass('col-md-3').append(
$('<img>').attr('src', item.img),
$('<div>').addClass('name').text(item.name),
$('<div>').addClass('category').text(item.category),
$('<div>').addClass('price').text('Price: ' + item.price + 'L.E')
)
);
//the below code is to create a new row after filling each row with 3 display columns
if ( rows.children().length >= 3 ) {
$('#content').append(rows);
rows = $('<div>').addClass("row");
}
}
}
// Flush any rows that were not yet added:
if ( rows.children().length ) {
$('#content').append(rows);
}
}
// Sample data
var products = {
fruit: [{
name: 'apple',
price: 2.20,
img: "https://www.colourbox.com/preview/7011130-apples-on-table-and-knife.jpg",
category: 'fruit'
}, {
name: 'kiwi',
price: 3.10,
img: "https://www.colourbox.com/preview/10157893-kiwi-fruit.jpg",
category: 'fruit'
}, {
name: 'banana',
price: 1.50,
img: "https://www.colourbox.com/preview/6294218-banana.jpg",
category: 'fruit'
}],
vegetables: [{
name: 'lettuce',
price: 0.90,
img: "https://www.colourbox.com/preview/2347661-fresh-salad-leaves-assortment-in-a-basket.jpg",
category: 'vegetables'
}, {
name: 'radish',
price: 1.60,
img: "https://www.colourbox.com/preview/3602479-red-radish.jpg",
category: 'vegetables'
}]
};
add_to_page(products);
.col-md-3 { display: inline-block; margin: 5px }
img { max-width: 100px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container full-width">
<div id="content"></div>
</div>
Append all your dynamic html to an element stored in a variable then append that variable to the DOM. that selector wont work bc the element you are trying to access doesnt exists yet.
Do something like:
var el = $('<div' + id + '></div>')
el.append(your row constructed html)
Then append that to your rows at the end of the 2nd for loop.
EDIT
for(.... row iteration code) {
var el = $('<div' + id + '></div>');
el.append('your image goes here');
el.append('name element');
...
rows.append(el);
}
Use #trincot's superior answer, but note that you can also pass an entire HTML string into jQuery's .html(). E.G:
function add_to_page(products) {
var $content = $("#content"),
cols=3, //number of columns
$row,
i=0;
for (var category in products) {
for (var item of products[category]) {
if(i%cols == 0){//add a new row
$row = $("<div class='row'></div>");
$content.append($row);
}
//add the item to the row
$row.append($("<div class='col-md-"+cols+"' id='" +item.id +"'><img src='"+item.img+"' /><div class=name>"+item.name+"</div><div class=category>"+item.category+"</div><div class=price>Price: "+item.price+"L.E</div>"));
i++;
}
}
}
var products = {
"jam" : [
{"id":1,"name":"strawberry", "category":"jam", "price":123, "img":"pic.gif"},
{"id":2,"name":"rasberry", "category":"jam", "price":456, "img":"pic.gif"},
{"id":3,"name":"madberry", "category":"jam", "price":123, "img":"pic.gif"},
{"id":4,"name":"sadberry", "category":"jam", "price":456, "img":"pic.gif"}
],
"bees" : [
{"id":4,"name":"baz", "category":"bee", "price":1, "img":"pic.gif"},
{"id":5,"name":"buzz", "category":"bee", "price":2, "img":"pic.gif"}
]
};
//console.log(products);
add_to_page(products);
.row {display:block; border:1px solid blue;}
.row div[id] {display:inline-block; border:1px solid red; width:100px; margin:5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container full-width">
<div id="content"></div>
</div>
You need to restructure the code.. are you able to find the element first
rows.append($("")
Instead use products.category [i].id then use jQuery wrap () to wrap the columns to row .
I'm creating an Dynamic form in angular js and when I'm adding new input fields as table row,and when pushing these objects into an array, previous element is replaced with copy of new element. Keys are same but values are different and also adding 'id' key before pushing into array.
JS
else if (el.type === 4) { //table
var x = 0;
$scope.row = []; //to store KEY OF table
$scope.thead = []; //store the heading of the table | also to make row structure
$scope.myFm[el.value] = []; //store row of table [ INVOICE ] myFm.invoice
$scope.colInput = {}; //values of input of each row
$scope.colInput.id = 0;
$scope.rowIndex = 0;
//iterate over column_heading
el.column_heading.forEach(function(elem) { //objects in column_heading
$scope.row[x] = elem.val; //the object with key names of row
$scope.thead.push(elem); //column headings
x++;
})
//pusing each row to myFm[el.value] | invoice
$scope.addNew = function(rowObj) {
// $scope.rowIndex++;
console.log('ROW ', rowObj);
rowObj.id = $scope.rowIndex;
$scope.myFm[el.value].push(rowObj);
console.log("Invoice", $scope.myFm[el.value]);
$scope.rowIndex++;
console.log("ROW", rowObj);
}
var row = "<tr ng-repeat='r in myFm." + el.value + " track by id' ><td ng-repeat='i in row'><input ng-model='colInput[i]' class='form-control' placeholder='Enter {[{ i }]}'></td></tr>"
item = "<label>" + el.heading + "<button ng-click='addNew(colInput)' class='m-l-lg btn font-bold'>ADD NEW</button></label> <table class='table'><thead><th ng-repeat='th in thead'>{[{ th.name }]}</th><thead>" + "<tbody>" + row + "</tbody><table>";
}
return item
}
// adding each element from list to DOM. $compile is needed to add the modified element to DOM
$scope.data.forEach(function(el) { //traversing over json object from the server
var item = verifyItem(el);
var linkFn = $compile(item);
var content = linkFn($scope);
element.append(content);
});
// adding the submit button to DOM
var linkFn = $compile('<button type="submit" ng-click="submitFm()" class="m- t-lg m-b-lg btn btn-danger">Submit </button>');
var content = linkFn($scope);
element.append(content);
When i',m passing 'colInput' to the 'addNew' function, and adding 'id' key each time i push new object to array '$scope.myFm[el.value]', the duplicates are being created ie: the newly added is replacing the previous objects, hence i cant 'ng-repeat' it by 'track by id'.
CONSOLE
Invoice Array [ Object, Object, Object ]
these three objects have values of last pushed object.
how do i fix it.
[![enter image description here][1]][1]i have a nested table , I want to having button to generate the row data to info.php by post method (looks like info.php?user = data[0] & key2 = data2) in one column for each row ,
I have one button but I need one button and perform some MySql when they are clicked to get the row data .
when click the button will get to every columns data in the row and post these data to info.php and view in popup window,
How can I perform post the row data in the nested datatable to other php using the button?
my code
click the button ,cannot get the row data ?
$('#example tbody').on( 'click', 'button', function () {
var index = $(this).closest('tr').index();
var data = table.row( $(this).parents('tr') ).data();
alert("References is "+ data[0] +"and section is "+ data[ 1 ]+ " and Stature Titles is "+data[2] );
} );
-UPDATED
just add class for button class='button-info'
columns:[
{ data:'name' },
{ data:'position' },
{ data:'salary' },
{
"targets": -1,
"data": null,
"defaultContent": "<button class='button-info'>Click Me!</button>"
}
]
first assign index value for every parent row
$("table tbody tr").each(function(index) {
$(this).attr('index', index);
})
then add new event for click event of that button and get the parent tr index
just get the index of your selected parent row using data attribute "index" added above
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
and to get your current row in nested data
var index = $(this).closest('tr').index();
so this is the final
$('table').on( 'click', 'td .button-info', function () {
var parent = $(this).closest('table').parents('tr').index();
var parentIndex = $('tbody tr:nth-child('+(parent)+')').attr('index');
var currentIndex = $(this).closest('tr').index();
var data = sections[parentIndex][currentIndex];
console.log(data);
return;
window.open("/info.php?name=" + data.name + "&sal=" + data.salary);
} );
See this updated JSFiddle
I have an object, say,
var LocSpecs=[{Address:"xxxxxx",SF:"1,200",YearBuilt:"xxxx"},
{Address:"xxxxxxx",SF:"1,950",YearBuilt:"xxxx"}.......}];
Over 200 key/values in the object.
I need to loop through and grab the values that meet a value and display said data on a table.
I get the for() and if(). I just don't quite get the appending the table to show only the records that meet the criteria.
resulting table would display on a
document.getElementBy("xxxx").innerHTML=myTable;
Assuming that you need to display rows based on some value in the object.
Create a function that builds a row when condition is satisfied.
LocSpecs.forEach(function(elm) {
if(elm.SF) { // your criteria
addRow(elm);
}
});
function addRow(elm) {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = elm.Address;
cell2.innerHTML = elm.YearBuilt;
}
I give you a ES6 alternative method to make a table. Using the DOMTableElement interface is inherently slower when used in JavaScript then adding pure HTML to the page and letting the browser's parser do it (That is what browsers are designed to do after all, parse and display HTML)
It uses Array.filter() to filter the records.
It uses Arrow functions to reduce the amount of code.
It uses Template strings to create the HTML for the table.
var locSpecs=[ // some data with random addresses added
{Address:"691 Union Street Herndon, VA 20170",SF:"1,950",YearBuilt:"1922"},
{Address:"939 Laurel Drive Pawtucket, RI 02860",SF:"1,950",YearBuilt:"1922"},
{Address:"176 Redwood Drive Ankeny, IA 50023",SF:"1,850",YearBuilt:"1932"},
{Address:"621 Sycamore Lane Flint, MI 48504",SF:"1,750",YearBuilt:"1932"},
{Address:"190 Canterbury Court Bountiful, UT 84010",SF:"1,350",YearBuilt:"1922"},
{Address:"461 3rd Street West Coram, NY 11727",SF:"1,950",YearBuilt:"1922"}
]
function createTable(data,filter,cellOrder,elementID,title){
// defined functions needed
function createRow(record){ // create a row
var str = ""; // string to hold the row HTML
cellOrder.forEach( // for each field in order
// want it to look good so add the cell class and the field class
name => str+=`<td class='${fieldClassPrefix+name}' >${record[name]}</td>`
);
return `<tr>${str}</tr>`; // wrap a row tab and return the new HTML for row
}
function createHeader(){ // created the header
var str = ""
cellOrder.forEach(name => str+= `<td class='${fieldClassPrefix+name}' >${name}</td>`);
return `<thead><tr>${str}</tr></thead>`;
}
// define variableds
var HTML, tableContainerElement,fieldClassPrefix; // you should not see any var tokens past this point
HTML = ""; // string to hold the new table HTML
fieldClassPrefix = "FF_"; // prfix for field class names
// find the element that will contain the new table
tableContainerElement = document.getElementById(elementID);
if(tableContainerElement !== null){ // make sure we found it
HTML += `${createHeader()}<tbody>`; // Add the header and begin the body
data.filter(record => filter(record)) // filter records
.forEach(record => HTML+=createRow(record)); // add filteredrecords
// now put it all together and put it on the page
tableContainerElement.innerHTML = `<div>${title}</div><table>${HTML}</tbody></table>`;
return true; // incase you need to know it worked
}
return false;
}
// create the click events and have them create the tables they need
document.getElementById("But1").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return Number(record.SF.replace(",","")) < 1800;
},
"SF,YearBuilt,Address".split(","),
"tableContainer",
"Records with a SF under 1800"
);}
);
document.getElementById("But2").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return Number(record.YearBuilt) > 1922;
},
"SF,YearBuilt".split(","),
"tableContainer",
"Records built after 1922"
);}
);
document.getElementById("But3").addEventListener("click",
function(){createTable(
locSpecs,
function(record){
return record.YearBuilt === "1922";
},
"SF,Address".split(","), // Dont need year
"tableContainer",
"Records built in 1922"
);}
);
// show the default table
createTable( // display all records and fields
locSpecs,
function(){return true; }, // filter function true for all
"Address,SF,YearBuilt".split(","),
"tableContainer",
"All records."
);
input {
cursor:pointer;
}
but:hover {
background:#7dF;
}
div {
width:100%;
}
table {
border:black 2px solid;
width:100%;
}
thead {
font-weight:bold;
text-align:center;
border:black 1px solid;
}
thead .FF_SF {
background:#dfffdf;
text-align:center;
}
thead .FF_YearBuilt {
background:#efdfff;
text-align:center;
}
thead .FF_Address {
background:#ffefdf;
text-align:center;
}
.FF_Address {
background:#ffddcc;
}
.FF_SF {
background:#ccffdd;
text-align:center;
}
.FF_YearBuilt {
background:#ddccff;
text-align:right;
}
<div>Select an option "Sorry IE ECMAScript6 browsers only."</div>
<input value="SF less than 1800" id="But1">
<input value="Year Over 1922" id="But2">
<input value="Year 1922" id="But3">
<div id='tableContainer'>