I have a table in which the rows are dynamic and the values come from database.
for eg my table is as follows:-
name|email
xyz|xyz#gmail.com
pqr|pqr#gmail.com
I have kept the names as link on clicking of which a form opens below with the same field as of table i.e
name:----
email: ----
so now what i want is with opening of the form i also want that the form should get prefilled with values that are there in table ..
for eg:- if a user clicks pqr then a form should get opend with values in it..
name : pqr
email : pqr#gmail.com
I made a javascript function where i pass the userid of the username that the user clicks..and in that i function i did the following :
var id=userid;
var row = document.getElementById(id);
var inputs = row.getElementsByTagName("td");
document.getElementById("fname").value = inputs[0].innerHTML;
document.getElementById("email").value = inputs[1].innerHTML;
and as i am using
inputs[0].innerHTML;
it prints the name like this :
<font size="4">xyz</font>
but I want only 'xyz' in my textbox..for that when I did :
inputs[0].value;
it gave me its value as undefined...why is it so?
please someone guide on getting the form filled with values of the row.
I'm making a few assumptions here. See this fiddle for working code: http://jsfiddle.net/G6Q5X/
Here's a basic table.
<table id="list">
<tr>
<td>Name 1</td>
<td>Email 1</td>
</tr>
<tr>
<td>Name 2</td>
<td>Email 2</td>
</tr>
</table>
First you want to get the table by ID and get the rows that it contains:
//nodeList of all rows in the table
var table = document.getElementById('list').children[0].children;
Then add an event listener to each link:
for(var i=0, len=table.length; i<len; i++){
var link = table[i].children[0].children[0];
link.addEventListener('click', getInfo);
}
The callback for the event listener will call a function, I used one I called "getInfo":
var getInfo = function(){
var name = this.innerHTML;
var email = this.parentNode.parentNode.children[1].innerHTML;
alert('Your name is: ' + name + ' and email is: ' + email)
}
I hope this helps.
Related
can someone give me tip how to slove problem. Am building Order Managment System app using PHP, MYSQL, HTML and JS.
Order information is stored in one db table and
Order Products is sotred in second db table which cointains two foreign key (order_id and product_id). Order can have many products!
What is problem
The problem is that I don't know how to get html table rows and put that rows in array, and that array i need to send via ajax to php where i will process.
I was thinking the following:
When the user selects a product from the drop-down list, enters the quantity and presses the "ADD PRODUCT" button.
In javascript, I create an event for a button ('click') where after event is triggered I will dynamically create a new row in the table using js insertRow().
In the columns of the rows I saved the values in the form fields. Maybe I was wrong there.
`id.innerHTML = '<input type="text" value="'+data[0]['id']+'" id="id-'+data[0]['id']+'";
Products is successfully added as rows with values to the table.
I'm not asking you to do my job. I just want you to advise me how it should be done in the right way.
HTML
<table id="document_items_table">
<thead class="table-light">
<tr>
<th width="10%">#</th>
<th>Šifra</th>
<th>Naziv</th>
<th>Količina</th>
<th>JM</th>
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript
// add item to document
$("#btn_add_document_item").on('click', function(e) {
var data = $('#select2-proizvodi').select2('data');
// add table row
var table = document.getElementById('document_items_table');
var row = table.insertRow(-1);
var id = row.insertCell(0);
var code = row.insertCell(1);
var name = row.insertCell(2);
var qty = row.insertCell(3);
row.setAttribute('id', 'row-'+table.rows.length);
id.innerHTML = '<input type="text" value="'+data[0]['id']+'" id="id-'+data[0]['id']+'" name="item[]["id"]" ;
code.innerHTML = '<input type="text" value="'+data[0]['code']+'" name="item[]["code"]";
name.innerHTML = '<input type="text" value="'+data[0]['text']+'" name="item[]["name]";
qty.innerHTML = '<input type="text" class="form-input" value="'+$("#kolicina_input").val()+'" name="kolicina[]["kolicina"]" ;
});
PHP is not a problem.
Check image
This is how I would have done it personally :
What I understand : You want to be able to save mutiple lines in the same time (because each line is a diffrent product of the same order for exemple)
You create a table where each line is a product and each cell of this line is the product info (name, qty, price, etc...)
When you click "save" button it has to trigger an ajax request that will call a php page, this page will cretate a new order and return the id as a response to the request.
Now you can loop throw your table rows, for each row you send an ajax request to a php page (data of this request is row cells + order_id you got previously)
Your php will recieved data from the ajax request and store it in your db table (order product)
I hope it answer your question, if you need help to write a part of this code feel free to ask me ;)
Maxime
How to get data froms table rows :
HTML :
<table id="table-products">
<thead>
<tr>
<th>Label</th>
<th>Qty</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Product 1</td>
<td>4</td>
<td>35</td>
</tr>
<tr>
<td>Product 2</td>
<td>8</td>
<td>12</td>
</tr>
<tr>
<td>Product 3</td>
<td>2</td>
<td>99</td>
</tr>
</tbody>
JS :
let table = document.querySelector('#table-products');
let headers = [...table.rows[0].cells].map(th => th.innerText);
for(let row of [...table.rows].slice(1, table.rows.length)) {
let product = Object.fromEntries(new Map([...row.cells].map((cell, i) => [headers.at(i), cell.innerText])));
console.log(product);
}
I've a PHP file which is a view (so mainly HTML) composed of several tables.
When the user click on one of the button, I want that the variables that are into my cells (and into the correct table) are sent to a Table in my Database.
To do this i'll use AJAX later, but at the moment i've a problem using JS/Jquery.
So I did something like this :
$('.boutton').click(function(){
$(?).find('td input').each(function(){
console.log($(this));
console.log($(this).val());
var iValue = $(this).val();
var sAllId = $(this).attr('id');
var sName = $(this).attr('name')
});
});
My table and buttons are into a div which has as id "table" + the number of the table.
I don't know what to do since I want this to work on every table, and on every button. It has to select only the td input that is into the table where the button was clicked.
My HTML is into a variable $sHtml since everything in this table are made of datas (in my DB) but it should be something like this :
<table id = "domaine-1-south">
<tr>
<th>BlaBla</th> // Several times
</tr>
<tr>
<td>Blabla</td>
<td><input id = "1#1#1#" name="high"></td>
<td><input id = "1#1#1#" name="mid"></td>
<td><input id = "1#1#1#" name="low"></td>
</tr>
<tr>
<td>Blabla</td>
<td><input id = "1#1#2#" name="high"></td>
<td><input id = "1#1#2#" name="mid"></td>
<td><input id = "1#1#2#" name="low"></td>
</tr>
For the id 1#1#1# the last 1 is for the number of the line and the second one is for in which table I'm.
You could use "start with" selector ^= to select all tables that have an id start with table :
$('[id^="table"]').find('td input').each(function(){
But in your OP you want to select the specific table related with the clicked button .boutton, so i guess that you have this button inside the table so you could select the current table using :
$(this).closest('table[id^="table"]').find('td input').each(function(){
Hope this helps.
I want to pass all datas stored in the table in my template. The table is growing by user's choices. My project is about a food ordering system and what i'm trying to do is, when user adds menus to its basket, and make an order, how can i pass the values to my view to save them to my db. I know about forms but my table is not static.. I can't imagine how it will be big.
My add row func:
$(document).ready(function(){
var sum = 0;
$(document).on('click', '.myaddButton', function() {
var $foodname = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text();
var $foodprice = $(this).closest("tr") // Finds the closest row <tr>
.find(".rn") // Gets a descendent with class="nr"
.text();
$('#carttable').prepend("<tr class='danger' id ='myTableRow'><td>"+$foodname+"</td><td class='price'>"+$foodprice+"</td> <td> <button class='deletebutton btn btn-danger' type='button'> <span class='glyphicon glyphicon-trash'></span> </button> </td></tr>");
});
$(document).on('click', '.deletebutton', function() {
$('#myTableRow').remove();
//$('.price').each(function() {
// var $price = $(this);
//console.log($price);
//sum += parseInt($price.context.innerHTML);
//});
//$('#total').html(sum);
//sum = 0;
});
});
</script>
My Table
<table border="1" class="table" id="menutable" name="menutable">
<tr class="danger">
<tbody>
{%for a in list%}
<tr class= {% DoRandom %}>
<td><b> {{a.name}}</b> </td>
<td class="nr">{{a.description}}</td>
<td class="rn"><p>{{a.price}}</p></td>
<td id="addbutton" > <button class="myaddButton btn btn-success" type="button">
<span class="glyphicon glyphicon-plus"></span> </button> </td>
</tr>
{%endfor%}
</tbody>
</table>
If you want to use little bit higher technique of form processing, then you should look at question Making a Django form class with a dynamic number of fields...
Second "simple" solution is to add hidden input values (which will contain food_id and quantity) together with name and price (during prepend), and wrap your table in form. E.g
var $food_id = ... // some how get food id
var $quantity = 1; //1 for now, but you can add increase and decrease functionality
...
// in prepend text
... + "<input type='hidden' name='food-" + $food_id + "' value='" + $quantity + "' >" + ...
And in your template you should add <form> before <table> (and </form> after </table> tags), or use serialize if you are using ajax.
Third solution is to use JS object as cart, and encode it to Json before form submittion. E.g.
//in your javascript global scope
var js_food_cart = {};
....
// then on click
$food_id = ... ;// yes, again you need food id
$quantity = 1; // or something elese
js_food_cart[$food_id] = $quantity;
....
// then somwhere in before submit, code assumes that you have form with my_cart hidden input
$('input[name=my_cart]') = JSON.stringify(js_food_cart);
Then in view you should parse your json value of my_cart input. In template you should add form with hidden field to pass cart value.
This approach more convenient if you will implement ability to increase/decrease quantity of food.
Thanks, i resolved the issue by casting my food objects to json and post by AJAX post.
I have this structure into my html.
<table border="1" cellpadding="1" cellspacing="2">
<thead>
<tr>
<th>Name</th><th>Age</th><th>Address</th><th>Option</th>
</tr>
</thead>
<tbody>
<tr>
<td>here is the name</td>
<td>here is the age</td>
<td>here is the address</td>
<td><button class="update">update</button></td>
</tr>
<tr>
<td>here is the name2</td>
<td>here is the age2</td>
<td>here is the address2</td>
<td><button class="update">update2</button></td>
</tr>
</tbody>
</table>
as you can see from the above structure, the display will be this.
table header = Name, Age, Address, Option.
table body = here is the name, here is the age, here is the address, button update
table body = here is the name2, here is the age2, here is the address2, button update2
now what Im trying to do is when I click the update button, i must able get the content of the address td to name td at the single same row and each must be stored in a specified variable e.g. ($name, $age, $address). assume i have mutiple row, I must able to retrieve only the content of address td to name td of the same row. To be more precise, as the structure above, I must able to get the 'here is the name', 'here is the age', 'here is the address' and put each in a specified variable e.g. ($name, $age, $address) when I click the u"update" button and not the "update2" button.
so far what I tried is.
$('.update').click(function(){
$address = $(this).prev('td').content();
alert ($dateposted);
});
but seems not returning anything. Any help would be greatly appreciated. Thank you!
Here this is the button, which does not have a previous sibling, the td you are looking for is the previous sibling of the td parent of the clicked button, also you have to use .text()/.html() to get the contents
$address = $(this).parent().prev('td').text();//$(this).closest('td')
Here is another way to do it. After you get all the previous divs then loop them to set the value to the correct variable.
$('.update').click(function () {
var contents = $(this).parent().prevAll('td');
var name;
var age;
var address;
for(i = 0; i<contents.length; i++){
var currentContent = $(contents[i]);
switch(i){
case 0:
name = currentContent.text();
break;
case 1:
age = currentContent.text();
break;
case 2:
address = currentContent.text();
break;
}
}
console.log(address, age, name);
});
For working example, please refer to http://jsfiddle.net/zeskysee/72j1oaqb/4/
Hope this help :)
I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')