I have a simple table filled with rows from a MySQL database, the HTML part looks like this
<tbody>
<?php while($row = mysqli_fetch_row($result)){ ?>
<tr class="rows" id="<?php echo $row[0]; ?>"> // the id is an auto incremented int
<td id="col1"><?php echo $row[1]; ?></td>
<td id="col2"><?php echo $row[2]; ?></td>
<td id="col3"><?php echo $row[3]; ?></td>
<td id="col4"><?php echo $row[4]; ?></td>
<td id="col5"><?php echo $row[5]; ?></td>
</tr>
<?php } ?>
</tbody>
It gets the job done and I have a nice table. Now I want that if I click on a row, i get five variables with the values of the cells.
The problem what stopped me was to get the <td> element. This is what I tried in the external javascript file:
var rows = document.getElementsByClassName('rows');
for (var i=0; i<rows.length; i++){
rows[i].onclick = function(){
console.log(this.getElementById('col1')); // I tried to print it first
}
}
The console responded this: Uncaught TypeError: undefined is not a function.
Then I tried console.log(rows[i].getElementById(vonalkod));, but it responded Uncaught TypeError: Cannot read property 'getElementById' of undefined
If I only write console.log(this); then it prints what I expect, the whole row in html.
So my question is that what is the syntax to get those cells by ID?
What you can do to get the contents of a cell is
document.getElementById('col1').innerHTML
Now, having said that, it will only work if you have ONE col1: if you have more than one of these <tr>s each will have five tds like <td id=col1>, the same for the rest of the id-s. That's invalid HTML. Consider replacing those id-s with classes, or with additional PHP.
Or, better yet, you can forgo all these clumsy id-s entirely and use something like:
rows[i].onclick = function() {
console.log(this.childNodes[0].innerHTML); // col1
console.log(this.childNodes[1].innerHTML); // col2
// ... etc
}
It doesn't work because the object this is a HTMLTableRowElement (see http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/html2/HTMLTableRowElement.html)
Here a library as jQuery comes very handy. Your script written using jQuery is as easy as
jQuery('.rows').click(function(){
alert(jQuery(this).children('#col1').text());
});
Related
I have a table of customers. Each customer has a first and a last name. The two text fields of the table are editable. So users can update the information when they press Save. The problem is that I cannot get the specific row information,I only get the first row results
I tried to match to the names with the input field but I had no success.
<?php foreach($customer as $each){ ?>
<td class="first_name" id="first" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" id="last" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td > <button type="button" onclick="save('<?php echo $each['first_name'];?
>','<?php echo $each['last_name'];?>');" >Save</button></td>
<? } ?>
<script type="text/javascript">
function save(first,second) {
<?php foreach($customer as $each){?>
var first_name = "<?php echo $each['first_name']?>";
var last_name = "<?php echo $each['last_name']?>";
if (first_name==first && last_name == second){
var fname = document.querySelectorAll(".first_name");
console.log(fname[0]);
}
<?php } ?>
}
</script>
You would have to use a different query selector. Assign a classname or an attribute to the elements you want to select (e.g name for querying with .name) then querySelectorAll method will return an array of the elements that matched your query.
The main problem that I see is that you create unnecessary foreach loop inside a javascript function using php.
You can dynamically create your table and the contents inside it, that's fine. But the javascript does not care about that and you should not create javascript with php. So I would do it this way.
I wrap the td's in tr's cause i'm assuming you are putting that data in tr.
<?php foreach($customer as $each){ ?>
<tr class="customer-row">
<td class="first_name" contenteditable="true"><?php echo
$each['first_name']; ?></td>
<td class="last_name" contenteditable="true"><?php echo
$each['last_name']; ?></td>
<td><button type="button" class="save">Save</button></td>
</tr>
<? } ?>
Then outside the php foreach loop i would create my script.
<script type="text/javascript">
var saveBtn = document.querySelectorAll(".save");
for(var i = 0; i < saveBtn.length; i++) {
// attach click event to every button.
saveBtn[i].addEventListener("click", function() {
var _this = this;
var _tr = _this.closest(".customer-row");
var fname = _tr.querySelector(".first_name").innerText;
var lname = _tr.querySelector(".last_name").innerText;
console.log("Name: ", fname + " " + lname");
// below you can implement your check name logic...
}
}
</script>
I'm not 100% sure if my js will not throw errors, but it should give you an indication that you should separate your server-side from client-side logic.
I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>
You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}
I am trying to set some fields of a form with the values of an array.
I have an array like this:
Array
{
'elementID1' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
'elementID2' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
...
}
The array is filled with the response of a webservice to whom I sent some parameters with a form. Once I filled the array, I draw a table and iterate over the array.
<table width = "100%" border = "1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>View details</th>
</tr>
<?php
foreach($array as $id => $detail)
{
echo "<tr>";
echo "<td>";
if(array_key_exists('id1', $detail))
echo $detail['id1'];
echo "</td>";
echo "<td>";
if(array_key_exists('id2', $detail))
echo $detail['id2'];
echo "</td>";
echo "<td>";
if(array_key_exists('id3', $detail))
echo $detail['id3'];
echo "</td>";
echo "<td>";
echo "View more";
echo "</td>";
echo "</tr>";
}
?>
</table>
Now, here comes the problem, as you can see there is a fourth column called View details, this column is filled with a hyperlink that calls a javascript function with the elementID value of the specific row as parameter.
A little more below I have the script:
<script>
function equisYe(id)
{
var equis = "<?php echo $array['" + id + "']['IncidentID']; ?>";
alert(equis);
}
</script>
When I click on the hyperlink doen't happen anything, I think the problem has something to do with the special characters inside the quote punctuations. In my browser, when I inspect one of the hyperlinks, it shows the following message inside de scripts tags:
function equisYe(id)
{
var equis = "<br />
<b>Notice</b>: Undefined index: + id + in <b>
";
alert(equis);
}
That means, for some reason, the strings aren't concatenating, and if I delete a 'p' from php tag in the equis var like this:
var equis = "<?ph echo $array['" + id + "']['IncidentID']; ?>";
Then the alert shows this:
"<?ph echo $array['10']['IncidentID']; ?>"
So, it works when it doesn't have the php tags.
The other answer is correct, but not explaining it at all (or even politely). The PHP stuff runs before your Javascript stuff does. You'll never get this to work this way, unfortunately. If it was the other way around, it might work, but this isn't going to work the way you have it.
The only way to have something like this working is to have the ID value chosen in advance and have PHP set something in Javascript. Javascript can never set a PHP value simply by virtue of PHP being run prior to the page being served and Javascript being run after the page is served.
dude... javascript executes on client(browser) and php on server; you CANNOT do that
try to use <? ?> instead of <?php ?>
Everyone is correct in that you can't simply call PHP functions from Javascript without performing some kind of HTTP request.
Since you already have the "IncidentID" in php while you're generating the page, you can simply write it to the page.
instead of
echo "<td>";
echo "View more";
echo "</td>";
do
echo "<td>";
echo "View more";
echo "</td>";
You can use data attribute to pass the $id to js, always using the DOM.
Check this: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Then use a click event in "view details" to get the data from element and trigger the function, this way you will be abble to work with it
My script’s AJAX calls the following PHP file and prints a table with $attrib and text boxes.
Can somebody tell me how to collect the $attrib and text box in an array or something like that?
Code tried is giving values like "assetattrib%5B%5D=model". So please help me to correct this or show me a new way to do the same.
echo "<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=addattrib >";
while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib'];
echo "<tr bgcolor='white'>
<td class='value'>$attrib</td>
<td class='value'><input type=text name=assetattrib[] value = '' </td>
</tr>";
}
echo "</table>";
echo "<input type=submit name='btnSaveAsset' id = 'btnSaveAsset' value='Save' >";
I tried the code below.
$(document).on("click", "#btnSaveAsset", function() {
$(document.getElementsByName('assetattrib[]')).each(function() {
var x = $(this).serialize();
alert(x);
});
});
IMPORTANT:
PHP mysql_ extension is deprecated and using it represents a major security issue. According to php.net
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used.
Now the actual answer:
I suggest some changes in your HTML, if you can make them:
Wrap the table where the <input>s are into a <form> element
Give the generated <input>s the name attribute given by $attrib, for example <input name="user" />
If you cannot modify the PHP/HTML code let me know and we'll find a workaround
I updated your jsfiddle using this changes. Your PHP code should end up like this:
<form id="btnSaveAsset" onsubmit="return false;">
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id='addattrib'>
<?php while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib']; ?>
<tr bgcolor='white'>
<td class='value'><?php echo $attrib; ?></td>
<td class='value'><input type='text' name='<?php echo $attrib; ?>' /> </td>
</tr>
<?php } ?>
</table>
<input type=submit name='btnSaveAsset' id='btnSaveAsset' value='Save' />
</form>
Then, you collect your data with one of this options:
$(document).on("click", "#btnSaveAsset", function () {
var data = $("#myForm").serializeArray();
console.log(data); // Array of objects
});
OR
$(document).on("click", "#btnSaveAsset2", function () {
var tempData = $("#myForm").serializeArray();
var data = {};
$.each(tempData, function () {
data[this.name] = this.value;
});
console.log(data); // Just an object
});
Here is the jsfiddle updated: http://jsfiddle.net/jormaechea/sy0wx8gb/1/
Check your JS console (Press F12 and go to Console tab) to see the results.
Hi i'm working on a Web System, i have a script which displays information about equipment inventory in a company. This information is stored in a Database (MySQL) and i'm using an HTML table to display the information previously stored in a PHP Variable which holds the query ResultSet and using a While Loop in order to retrieve every value and display it in the table.
Everything is perfect at this point.
But i have added a Search button, in which the user enters the Equipment's ID to search for. Then, if the ID exists, i want to set to RED the border of the row that has the ID just found.
The problem is that when i try to get the ID of the row to be changed i get null from the Javascript which changes the style attribute of that row.
I use a While Loop to generate the HTML table, and i just have declared 2 rows:
One for the header of the table
One to display the data.
I tried to dynamically generate IDs for the second row (for example, if there are 3 computers, then there'll be 3 rows with different IDs, and these IDs are based on the current ID stored in a variable called $c1).
Then i just call the JS sending a variable that has the ID to search for (this ID is supposed to be the same as the row's ID) and set the Background of that row to RED. But i got the error "Cannot read property 'style' of null". I've search and the only thing i've found is that i have to wait until the document loads and then call the Js in order to search the element, but it didn't work.
PHP
<table>
<tr>
<td>ID del Equipo</td>
<td>Tipo</td>
<td>Marca</td>
<td>Modelo</td>
<td>Procesador</td>
<td>Memoria Ram</td>
<td>Detalles</td>
<td>Area</td>
</tr>
<?php
$i = 0;
while ($i<$num)
{
$c1 = mysql_result($result, $i, "ID del Equipo");
$c2 = mysql_result($result, $i, "Tipo");
$c3 = mysql_result($result, $i, "Marca");
$c4 = mysql_result($result, $i, "Modelo");
$c5 = mysql_result($result, $i, "Procesador");
$c6 = mysql_result($result, $i, "Memoria RAM");
$c7 = mysql_result($result, $i, "Detalles");
$c8 = mysql_result($result, $i, "Area");
?>
<tr id="<?php echo $c1; ?>">
<td><?php echo $c1;?></td>
<td><?php echo $c2;?></td>
<td><?php echo $c3;?></td>
<td><?php echo $c4;?></td>
<td><?php echo $c5;?></td>
<td><?php echo $c6;?></td>
<td><?php echo $c7;?></td>
<td><?php echo $c8;?></td>
</tr>
<?php
$i++;
}
?>
</table>
</section> //The end of the section where the info is displayed
<script type="text/javascript">
remarcarBusqueda(<?php echo $_SESSION['VALOR_BUSQUEDA'];?>);
//The $_SESSION ['VALOR_BUSQUEDA'] holds the value (ID) of the
//element to search that has been already checked in another script
</script>
JavaScript
function remarcarBusqueda(elemento)
{
rem = document.getElementById(elemento);
rem.style.background="red";
}
Notes:
I only got the null error
So i hope you guys can help me. Thanks.
P.S: I'm from Mexico, that's why the var names are in Spanish, sorry :)
UPDATE Here is the HTML output:
http://imgur.com/Y262vCe
UPDATE #2 If i change the tr ID to tr id="Row", for example, no matter what value i enter (1, 4 or 7), the 1st Row always gets Red, and i don't get the null error. Of course, i don't send any parameter to the JS, and in the line document.getelementById i put "Row" as parameter.
Is it $c1 is numeric value??
Try using this to fix:
<tr id="myTr<?php echo $c1; ?>">
...
<script type="text/javascript">
...
remarcarBusqueda('myTr' + <?php echo $_SESSION['VALOR_BUSQUEDA'];?>);
</script>
Note:
in HTML DOM, all objects should never using the numeric as id, because Javascript cannot access it.