Capture specific row information after calling blur event - javascript

Let's say that I have this table with two rows:
<tr>
<td contenteditable="true" data-group1="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
<tr>
<td contenteditable="true" data-group2="<?php echo $_GET['group']; ?>" class="no2" id="nom2" name="nom2"><?php echo $item[$i]; ?></td>
</tr>
The table is contenteditable which means, I can change the value inside the table. Currently, once the data have been manipulated, the data will be captured once the blur event is called. This is my script:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
$(document).on('blur', '.no2', function(){
var group= $(this).data("group2");
var no = $(this).text();
});
Based on this algorithm, let's say that I have manipulated the data from the first row which is referring to the class = "no1", it will then run this script as shown above:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
However, the number of rows for this table is not fixed. Therefore, this script is not helpful as we defined the function by ourselves based on the number of rows. Is there any way on how we can capture specific row information after calling the blur event so that we do not have to define quite a lot of similar functions.

You can use a common class on your trs and attach a blur event handler on its contenteditable td.
About your data-groupX attributes, just rename them all to data-group :
PHP
<tr class="common"> //Add your class here
<td contenteditable="true" data-group="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
Javascript
$(document).on('blur', '.common td[contenteditable]', function(){
var group= $(this).data("group");
var no = $(this).text();
});

Related

javascript insert new row same as first row when press enter in html table last row

I want to insert new row in html table when user press enter on keyboard. At beginning I already added first tr when create the table. In this tr, first td contain html dropdown list($select_chooseitem) that contain data from database.Second column is textbox. I want to use javascript to get first tr element set and create new row based on that. tr element set would be like:
<tr>
<td>first col</td>
<td>second col</td>
</tr>
I do not want to declare new tr element set. But, want to retrieve first tr element set from table. Is this possible?
$row_html ='<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>';
$html_complete='<!DOCTYPE html>
<html lang="en">
<head>
<script>
$(function () {
// Change the selector if needed
var $table = $(".mt-table-edit");
//addNewRow();
function addNewRow() {
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td><input/></td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13) {
addNewRow();
}
});
// add template after the last row
$table.find("tbody:last-child").append($tr);
// focus on firt input of newly added row
$tr.find("td:first input").focus();
}
});
</script>
</head>
<body>
<table class="mt-table-edit">
'.$row_html.'
</table>
</body>
</html>';
echo $html_complete;
//echo $query_tbltemplateitems;
Since first one not work, other method I tried was getting $select_chooseitem in javascript to create tr element set. I tried access php variable($select_chooseitem) in js by addNewRow('.$select_chooseitem.'); ,but not working. How is proper way to access php variable value from js?
<script>
$(function () {
var $table = $(".mt-table-edit");
var $row = $(".mt-table-edit").children("tr:first");
addNewRow('.$select_chooseitem.');
function addNewRow(var)
{
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td>var</td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13)
{
addNewRow(var);
}
});
$table.find("tbody:last-child").append($tr);
$tr.find("td:first input").focus();
}
});
</script>
I have tried declare variable in js and try to access in js in head of html. not successful too.
Example:
<?php
$select_chooseitem='<select>'.$option_list.'</select>';
?>
<script>
var select_chooseitem=<?php echo $select_chooseitem;?>;
</script>
Thanks in advance.
Kindly try the code snippet below.
$(document).on( 'keyup', '.name', function(){
if (event.which == 13 && $(this).closest("tr").is(":last-child")) {
var $tblbody = $('#mytable').find("tbody"),
$tbltrlast = $tblbody.find("tr:last"),
$trnew = $tbltrlast.clone();
$tbltrlast.after($trnew);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='mytable'>
<tbody>
<tr>
<td><input type='text' name='name' class='name' value='John Doe'></td>
</tr>
</tbody>
</table>
If you want to access the first child of tr you can use this:
$('table tr:first-child')
Since you are using jQuery this code might be useful.
This code searches for a table tag then selects the first tr tag
$('table tr:first-child')
You can also achieve this using plain css
table tr:first-child{
color: red;
}
The required markup for the row is constructed.
markup = "<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>"
The table body is selected to which the table rows to be added.
tableBody = $("table tbody")
Finally the markup is added to the table body.
tableBody.append(markup)
the solution Kaptian delivered seams like a good one, but he copys the last row of the Table. if you set newrow like that, it should do the job.
var newrow = $('#mytable tr:first-child').html();
Thank you for suggestion and answers. By using .clone().appendTo() and keyup(function(e), I'm able to add new row by enter on keyboard. Every time enter, it did add new row after last tr. But ,could not limit add row will execute only when enter in last td of last row.
$(function() {
// Change the selector if needed
var $table = $(".mt-table-edit");
//var $row = $(".mt-table-edit").children("tr:first");
addNewRow();
function addNewRow() {
var $tr = $table.find("tr:eq(0)").clone();
//$(".mt-table-edit").keyup(function(e) {
//$(".mt-table-edit tr:last td:last").keyup(function(e) {
$($table.find("tbody:last-child")).keyup(function(e) {
if (event.keyCode === 13) //test enter key press on keyboard
{
//$table.find("tbody:last-child").append($tr);
$table.find("tr:eq(0)").clone().appendTo($table.find("tbody:last-child"));
}
});
$tr.find("td:first input").focus();
}
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<html lang="en">
<body>
<table class="mt-table-edit" border="1">
<tr>
<td>first col</td>
<td><input type="text" name="order"></td>
</tr>
</table>
</body>
</html>
jsfiddle
Thanks in advance.

using javascript to build on php loop with classes only logging first result

I'm currently building a form and the data within it is build from a PHP Foreach loop
I'm using Javascript so that I can make the action of checking/unchecking a checkbox will make an ajax call.
The issue right now (using class names) is that when I click the checkbox and console log the data, each checkbox does trigger properly but it only console logs the first table row's data
So if my php loop builds 5 rows, each with their own values and their own checkboxes, each checkbox triggers the log but they each log only the first set of values.
What am I doing wrong here?
$(".addToLineup").click(function (e) {
var number = document.getElementsByClassName("number")[0].innerHTML;
var detail = document.getElementsByClassName("detail")[0].innerHTML;
var category = document.getElementsByClassName("category")[0].innerHTML;
updatedata.number = number;
updatedata.detail = detail;
updatedata.category = category;
console.log(updatedata);
)};
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="number">{{$list['GROUP']}}</td>
<td class="detail">{{$list['COVER']}}</td>
<td class="category">{{$list['CATEGORY']}}</td>
<td><input class="addToLineup" type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?></td>
</tr>
#endforeach
</form>

How to sum up multiple Inputs multiplied by value simultaneously

So, I have This Fiddle where I have a table that has an input and a cost. It also has a bit of jquery.
$( ".total" ).change(function() {
i = 1;
var input001 = document.getElementsByName(i)[0];
var cost001 = document.getElementById("cost" + i);
var total001 = input001.value * cost001.innerHTML;
var num = total001;
var total = num.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "1,");
document.getElementById("printchatbox").value = total;
i++;
});
This code multiplies the first input times the first Item Cost. I would like to find a way to repeat this 45 times (one for each item) without copy and pasting this code 45 times... If that is the only way to do it, I can do that... but I'm hoping to learn something and make my code significantly shorter at the same time. This table is generated by php, I just copied and pasted the html that was generated for the fiddle.
while($row = $result->fetch_assoc()) {
$row['ItemID'] = ltrim($row['ItemID'], '0');
?>
<tr>
<td><input type="number" class="total" name="<?php echo $row['ItemID']?>" value "<?= isset($_POST[$row['ItemID']]) ? htmlspecialchars($_POST[$row['ItemID']]) : "" ?>"></td>
<td><?php echo $row['ItemID']?></td>
<td><?php echo $row['ItemDescription']?></td>
<td id="<?php echo 'cost' . $row['ItemID'] ?>"><?php echo $row['ItemCost']?></td>
<td id="<?php echo 'value' . $row['ItemID'] ?>"><?php echo $row['ItemValue']?></td>
</tr>
<?php
}
?>
</table>
this is the PHP code on the website that creates the table...
this is the first row of the html table.
<tbody><tr>
<td><input class="total" name="1" value="" ""="" type="number"></td>
<td>1</td>
<td>Barrel Wrap 47"x31"</td>
<td id="cost1">39.38</td>
<td id="value1">47.25</td>
</tr>
and here is an image of the first 10 rows of the table.
if I have to change something in there, that is totally fine, I'm just hoping to keep the readability and reduce the redundancy.
Thanks
Here's your updated fiddle: https://jsfiddle.net/737v3qxr/2/
So I've changed a few things:
$( ".total" ).change(function() {
var name = this.name;
var quantity = this.value;
var cost = document.getElementById("cost" + name).innerHTML;
var total = quantity * cost;
items[name] = {cost, quantity}
new_total();
});
when you apply a function/listener to something, the this references the element itself, so you didn't need to do an extra i and i++ with it.
I've also introduced JSON (it's basically a dictionary in any other language), which helps with tracking prices.
Most of the code is just renamed since your logic wasn't actually too far off, just very clumsy and convoluted.
I've also added a new_total function, which doesn't really need to be a function in and of itself, but it's just my preference.
Finally I've added an id to your total to make it easier to track.
<input id="total" type="text" readonly id="printchatbox" name="total">
There's also some weird empty text which I'm assuming refers to your php, but you will have to deal with that yourself.
<input class="total" name="45" value="" ""="" type="number">
You can use the event handler argument as well:
$( ".total" ).change(function(e) {
var cost001 = document.getElementById("cost" + e.target.name);
var total001 = e.target.valueAsNumber * Number(cost001.innerHTML);
var prev = Number(document.getElementById("printchatbox").value);
document.getElementById("printchatbox").value = total001 + prev;
});

Get value from td

I print results from db. I am facing problem when I want to choose value from row. I was trying to pick up the value by entering button (last column) on value, and insert that value in local storage.
<table class="table table-bordered">
<thead>
<tr class="bg-grey">
<th>Broj </th>
<th>Boja </th>
<th>Količina</th>
<th><center><i class="icon-cart"></i></center></th>
</tr>
</thead>
<tbody>
<?php
while ($r=$m->fetch()) {
$id_print = $r['id'];
$boja = $r['Boja'];
$kolicina = $r['Kolicina'];
// var_dump($id_print);
?>
<tr>
<td><?php echo "R - " . $id_print;?></td>
<td><?php echo $boja;?></td>
<td><?php echo $kolicina;?></td>
<td><button id= "item" value='<?php echo $id_print;?>' onclick="save()" class="ion-ios-cart-outline"></button></td>
</tr>
<?php } ?>
</tbody>
</table>
I am using function to get value from td. But I always get empty var.
<script type="text/javascript">
function save() {
var items= document.getElementById('item').innerHTML;
localStorage.setItem('action', items);
}
</script>
I am not doing something good, If someone can tell me what to change in order to get results.
If your goal is to save the value of the button that was clicked, you don't need any ids at all.
The minimum-changes approach is to pass this into your handler as an argument, and then use the argument's value property in the handler's code:
<td><button value='<?php echo $id_print;?>' onclick="save(this)" class="ion-ios-cart-outline"></button></td>
<!-- Note ------------------------------------------------^^^^^ -->
then
function save(element) {
localStorage.setItem('action', element.value);
}
You might also consider adding type="button" to your button elements, since the default type of buttons is (to me, surprisingly) type="submit", so if you have those buttons in a form, they'll submit the form.
Re your comment:
That is exactly what I was looking for, but in table I have more rows and more could be selected. By doing this only one value is possible to select. Is it possible so save values in local storage by clicking on them
If you mean as an array, yes, you can do that. Here's one way:
function save(element) {
var actions = JSON.parse(localStorage.getItem("actions") || "[]");
if (actions.findIndex(element.value) == -1) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}
}
That maintains an array in local storage as JSON (since all local storage values are strings). The first part gets the existing array (if any) or a blank one (if none):
var actions = JSON.parse(localStorage.getItem("actions") || "[]");
Then we use the ES2015 (aka "ES6") function Array#findIndex (which can be polyfilled/shimmmed, see MDN) to see if the value is already in the array and, if not, we add it:
if (actions.findIndex(element.value) == -1) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}
If for any reason you don't want to shim/polyfill Array#findIndex, you can use the ES5 function Array#some instead:
if (!actions.some(function(e) { return e === element.value; })) {
actions.push(element.value);
localStorage.setItem("actions", JSON.stringify(actions));
}

Add New Field to Form and Save it to database

First Problem:
I want to add new field with a button, so everytime the button is clicked it will create new field. I try using Jquery but I am new in this kind of programming language, can someone help me? Am I doing it right?
HTML
<table>
<tbody>
<tr>
<td>
<?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?>
</td>
<td><input type="text"></td>
</tr>
</tbody>
</table>
<center><button id="addrow">Add Row</button></center>
Script
<script>
$(document).ready(function(){
$("#addrow").click(function(){
consoloe.log("asdasda");
$(tbody).append('<tr><td><?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?></td>
<td><input type="text"></td>
</tr>');
});
});
</script>
This is the error I get
This is The form look like
Second Problem:
I think I need to give a name or ID for this field, because I need to save it to a database, can you give me some advice about POST method to insert multiple records with mysqli? How can I loop the insert statement?
One things about your code first: 1. You neeed to also close the "select" element before ""
My advice solution:
Use jQuery to add new field like so
$("#addRow").click(function(){
$(tbody).append('<tr><td><select><option>Test1</option><option>Test2</option></select> </tr></td>);
});
Then to loop through your form before you submit it you can use PHP. All the fields would be in the $_POST[] suberglobal so foreach($_POST[] as $item){ //insert field in DB }
You can also use AJAX to submit the form and iterate over it's fields in jQuery:
$.each("tbody tr td select", function(field){
$.post("yourPHPfile.php", {name:field}, function(data){
//on success handler
});
});
Hope that helps!
You can do this by pure javascript , here is the example
var yourHTML="<td><select>";
yourHTML +="<option>--</option>";
yourHTML +="<option>--</option>";
yourHTML +="</select></td>";
yourHTML +="<td><input type='text'></td>";
function addRow(e){
var tab=e;
var rowCount=tab.rows.length;
var row=tab.insertRow(rowCount);
row.innerHTML=yourHTML;
}
Now call addRow() on click of button
$(document).ready(function(){
$("#addrow").click(function(){
addRow(document.getElementsByTagName("table")[0]);
});
});
LIVE http://jsfiddle.net/mailmerohit5/3outf4vm/

Categories