Onchange event is not detecting copy paste in input fields - javascript

I have so many Input fields in html table and I am using the code below to copy paste columns from excel directly to these input fields. and the code below is working great for copy paste columns from excel to this html input table fields. My problem is that I want onchange event for each input to detect when I copy paste and alert these values. cause then I can take each value was changed and change it in the database. The Onchange event does not detect change in value when I copy paste!
<table>
<thead>
<tr>
<th>Name</th>
<th>Unit</th>
<th >ID</th>
<th >Margin </th>
</tr>
<tbody>
<?php
$query = " select name,unit,Margin, id FROM Table1";
$stmt = $conn->query( $query );
$count=0;
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) )
{ ?>
<tr>
<td> <input onchange="send(this)" type="text" value="<?php echo $row['Name']; ?>"> </td>
<td><input onchange="send(this)" type="number" value="<?php echo $row['unit]; ?>" ></td>
<td><input type="number" value="<?php echo $row['ID']; ?>" ></td>
<td><input onchange="send(this)" type="number" value="<?php echo $row['Margin']; ?>" ></td>
</tr>
<?php } ?>
</tbody>
</thead>
</table>
<!-- Copy Paste in input fields -->
<script type="text/javascript">
$('input').on('paste', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
</script>
<script>
function send(value){
alert(value.value);
}
</script

I use this for my input for cut ,copy & paste
function send(value){
alert(value.value);
}
input here : <input onchange="send(this)" type="text" oncopy="send(this)" onpaste="send(this)" oncut="send(this)" type="text" value=""/>

Related

Adding array of value in javascript

I'm asking this question again and hope I get the answer this time, I have an array of number that adds and subtract on button click which works withonclick and a function created. I will like the sum up of the array 21998 and 11999 when this same button is click and will like to display the value in <p id=""sumTotal></p> find screenshot of what my array looks like:
I have an onClick function that multiple quantity with total every time - and + are clicked. I will like the sum-up of 21,998 and 11,999 when - and + are clicked. Below is what my HTML code and PHP script look like:
<p id = "sumTotal"></p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
And my javascript onclick looks like below code:
<script>
function clickMe(id) {
var price = document.getElementById(id+"_price").innerHTML;
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>
I will like to get the sum total of 21,998 and 11,999to <p id = "sumTotal"></p>
Call this function in the end of clickMe function.
function total() {
const priceElements = document.querySelectorAll('[id$="_totalPrice"]');
return [...priceElements].reduce((acc, curr) => acc + +curr.innerText, 0);
}
I was able to solve this myself, at first on the load of the page I sum up the all prices to get my initial sumTotal and did that in PHP with $subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));. So <p id = "sumTotal"></p> will be <p id = "sumTotal">echo array_sum( str_replace(",", "", $_SESSION['price']));</p> And inside my javascript I made the changes with the script, I get the value of sumTotal subtracted it from Price and add the sumTotal and new price after + or - to get the new sumTotal below is my update code:
<p id = "sumTotal">$subTotal_sum = array_sum( str_replace(",", "", $_SESSION['price']));</p>
<table class="table table-cart table-mobile">
<thead>
<tr>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<? for($i=0;$i<count($_SESSION['img_src']);$i++){ ?>
<tr>
<td class="price-col" id="<? echo $_SESSION['id'][$i].'_price' ?>" >₦<?php echo $_SESSION['price'][$i] ?></td>
<td>
<div onclick="clickMe(<?php echo $_SESSION['id'][$i]; ?>)">
<input type="number" value="1" min="1" max="10" step="1" data-decimals="0" required id = "<? echo $_SESSION['id'][$i].'_quantityCount' ?>">
</div><!-- End .cart-product-quantity -->
</td>
<td id = "<? echo $_SESSION['id'][$i].'_totalPrice' ?>">₦<?php echo $_SESSION['price'][$i] ?></td>
</tr>
<?
}
?>
<tbody>
</table>
<script>
function clickMe(id) {
var sumTotal = document.getElementById("sumTotal").value;
var price = document.getElementById(id+"_price").innerHTML;
var initialSumTotal = parseInt(sumTotal) - parseInt(price);
let finalPrice = price.replace(/[^a-zA-Z0-9]/g, '')
var quantity = document.getElementById(id+"_quantityCount").value;
var totalPrice = quantity * finalPrice;
document.getElementById(id+"_totalPrice").innerHTML = "\u20A6"+totalPrice.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
var sumTotal= parseInt(initialSumTotal)+parseInt(totalPrice);
// parsing the value to display on sub total
document.getElementById("sumTotal").value ="\u20A6"+sumTotal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>

php form building in loop, javascript only affecting first element

I'm currently building a form, and using a PHP loop to build the elements in a table which hold the values I'm submitting after clicking a checkbox.
<form id="saveLineup">
#foreach($lists as $list)
<tr style="text-align:center;">
<td id="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td id="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</td>
<td id="category">{{$list['CATEGORY']}}</td>
<td><input id="addToLineup"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo "checked='checked'"; ?>></td>
</tr>
#endforeach
</form>
My issue is, I have an id on the checkbox and id's on the values so I can only get the console log when I click the very first checkbox and it only logs the very first item. How can I change this so that I can submit with any checkbox in the table and it's associated values?
$("#addToLineup").click(function (e) {
var productNumber = document.getElementById("productNumber").innerHTML = productNumber;
var detailColor = document.getElementById("detailColor").innerHTML = detailColor;
var category = document.getElementById("category").innerHTML = category;
updatedata.productNumber = productNumber;
updatedata.detailColor = detailColor;
updatedata.category = category;
$.ajax({
url: "/test/addToLineup",
data: updatedata,
_token: phpVariables.csrfToken,
type: "POST",
beforeSend: function () {
showLoading(element);
},
success: function (data) {
location.reload();
},
});
});
Here is the solution to your problem, you need to use classes instead of IDs.
#foreach($lists as $list)
<tr style="text-align:center;">
<td class="groupNumber">{{$list['product']}} - {{$list['product_NAME']}}</td>
<td class="detailColor">{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}</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
Now, in your JS section, you can fetch them by their class:
var productNumber = document.getElementsByClassName("productNumber").innerHTML = productNumber;
var detailColor = document.getElementsByClassName("detailColor").innerHTML = detailColor;
var category = document.getElementsByClassName("category").innerHTML = category;
Note: If you're applying CSS styles to those elements via their ID, you can change #productNumber to .productNumber in your CSS or you can leave the ID tag with the same name as your previous code.
In PHP code
<form id="saveLineup">
<?php $i=0; ?>
#foreach($lists as $list)
<?php $i+=1; ?>
<tr style="text-align:center;">
<td id="groupNumber<?php echo $i ?>">.
{{$list['product']}} - {{$list['product_NAME']}}
</td>
<td id="detailColor<?php echo $i ?>">.
{{$list['detail']}}/{{$list['COLOR']}} - {{$list['description']}}.
</td>
<td id="category<?php echo $i ?>">.
{{$list['CATEGORY']}}
</td>
<td>
<input id="addToLineup<?php echo $i ?>"> type="checkbox" <?php if ($list['LINE_UP'] == 1) echo
"checked='checked'"; ?>>
</td>
</tr>
#endforeach
<input id="listcount"> type="hidden" value="<?php echo $i; ?>" >
</form>
Js function
$("#addToLineup").click(function (e) {
for(var i=1 ; i <= parseInt(document.getElementById("listcount").value); i++) {
Console.log(document.getElementById("productNumber"+i).innerHTML);
Console.log(document.getElementById("detailColor"+i).innerHTML);
Console.log(document.getElementById("category"+i).innerHTML);
}
});

Can't Un-disable checkbox after submit that have get its value from DB

I need your help about my problem. I've two table with checkbox, the first is show all the record from DB (using MySQL) and the second table get the data after I checked and submit from the first table.So I want to disable my checkbox in the first table after I checked and submitted the data to the second table, but if I want cancel the copy I check the second table so the checkbox in the first table will be enabled and the data in the second table will erase (because it just temporary variable for store another DB). In this code I'm using disable but it can't work where is the problem?
// this code for checked the checkbox that be chosen first
session_start();
if (count($_POST)){
//save choices to session
$_SESSION['select_DB']=$_POST['select_DB'];
}
function was_checked($i) {
if ($_SESSION['select_DB']){
if(in_array($i,$_SESSION['select_DB']) ) {
return "checked='checked'";
}
}
return "";
}
?>
// this one if cancel the submit
<script>
function openCB() {
document.getElementById("balik_DB[]").disabled = false;
}
</script>
//i'm using this to disable checkbox after submit
<script>
function closeCB() {
document.getElementById("balik_DB[]").disabled = true;
}
</script>
<!-- This code show table with checkbox that its value get from DB-->
<tbody>
<?php
include "db_connect.php";
$sql_select = $dt_bas->prepare("SELECT id_pegawai, nm_pegawai, tmp_lahir FROM pegawai");
$sql_select->execute();
while($row = $sql_select->fetch(PDO::FETCH_ASSOC)){
$id = $row["id_pegawai"]; // id
$nm = $row["nm_pegawai"]; // employe name
$tmp = $row["tmp_lahir"]; // birthday
?>
<tr>
<td><input type="checkbox" name="select_DB[]" id="select_DB[]" value=<?php echo"$id";?> <?=was_checked($id)?>/></td>
<td><?php echo "$id";?></td>
<td><?php echo "$nm";?></td>
<td><?php echo "$tmp";?></td>
<td>
Ubah
Detail
</td>
</tr>
<?php } ?>
</tbody>
<!--this the second table that get its value from the first table-->
<form>
<table border="1">
<thead>
<tr>
<th></th>
<th>ID</th>
<th>Nama</th>
<th>TTL</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php
// this code for get the data that is chosen from checkbox
include "db_connect.php";
if(isset($_POST['select_DB'])){
foreach($_POST['select_DB'] as $select=>$option_id){
$sql_select2 = $dt_bas->prepare("SELECT id_pegawai, nm_pegawai, tmp_lahir FROM pegawai WHERE id_pegawai = '$option_id' ");
$sql_select2->execute();
while($row = $sql_select2->fetch(PDO::FETCH_ASSOC)){
$id = $row["id_pegawai"]; // id
$nm = $row["nm_pegawai"]; // employee name
$tmp = $row["tmp_lahir"]; // birth place
?>
<tr>
<td><input type="checkbox" id="balik_DB[]" value="<?php echo"$id";?>"/></td>
<td><?php echo"$id";?></td>
<td><?php echo"$nm";?></td>
<td><?php echo"$tmp";?></td>
<td>
Ubah
Detail
</td>
</tr>
<?php }
}
}
?>
</tbody>
<tfooter>
</tfooter>
</table>
<input type="submit" value="Balik" onclick="openCB()"/>
</form>
The problem in id="balik_DB[]" because you fetch data from the database and dynamically create checkbox so what will happen when more than one checkbox would have same 'id'(id should be unique).So instead of using id ,you need to use class = "balik_DB[]".

Add Rows dynamically having unique input id's in td

The code below displays the 10 rows having three columns. the input id's are type_1,type_2,type_3,type_4,type_5 (and same for the rest two columns room_1 to room_5, quantity_1 to quantity_5).
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php for($i=1;$i<=5;$i++)
{?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php }?>
</thead>
</table>
Now My question is that I have a button ADD 5 ROWS.I want to generate the above rows dynamically each time the button is clicked and at the same time I want to handle the id's of the input like on first click the id's of first column will be type_1 to type_5 and on second click they should be type6 to type_10.
<button class="btn btn-success">ADD 5 ROWS</button>
You shoudl use ajax for such process.
PHP Script:
if( isset($_POST['send_row_request']) )
{
// process the request
$base_id = $_POST['base_id'];
$_SESSION['next_request_base_id'] = $base_id + 5; // setting this for the next request.
// get the data from DB. You have already written the function for you to get
// 5 rows of DB based on a base id give,
$result_array = get_db_data($base_id);
echo json_encode($result_array)
/***
Or if you are not comfortable with JSON you can loop through array and echo them
on each iteration
***/
}
And HERE is the jQuery AJAX :
$(document).ready(function(){
var base_id = $('#base_id').val();
$('myButton').click(function(){
$.ajax({
url : 'url_to_your_php_script',
data : ({send_row_request : 'true', 'base_id' : base_id});
success : function(msg)
{
// do the stuff here and don't forgot to update base_is hidden field on the last record process
}
})
});
});
And here is a simpel HTML. Note that you should save your last row's id of your first five-records into a hidden input with the id of for example #base_id. This value also should be changed on each use click on the button.
<input type='hidden' value='<?php echo $base_id; ?>' id='base_id' />
You can use the php session variable to dynamically create rows among page request:
<?php
session_start();
if(isseet($_POST['your_button_id']))
{
if(isset($_SESSION['row_id']))
$_SESSION['row_id']=$_SESSION['row_id']+1;
else
$_SESSION['row_id']=1;
}
?>
<table id="dgsv_admin" style="width:950px; height:460px;">
<thead>
<tr>
<th>Type</th>
<th>Room</th>
<th>Qty</th>
</tr>
<?php if(isseet($_POST['your_button_id']))
{
$row =$_SESSION['row_id'];
for($i=$row;$i<=$row+4;$i++)
{
?>
<tr>
<td><input id="type_<?php echo $i ?>" style="width:64px;" class="easyui-validatebox" data-options="required:true" /></td>
<td><input id="room_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" required="true" /></td>
<td><input id="quantity_<?php echo $i ?>" style="width:64px;" class="easyui-numberbox" data-options="required:true" /></td>
</tr>
<?php } $_SESSION['row_id']=$_SESSION['row_id']+4; } ?>
</thead>
</table>

How to know the number of textbox in a form using javascript

How do I determine the correct number of textbox (input type="text") in an html form using Javascript.
What I'm trying to do here is to compute the subtotal by providing the qty and price.
<script type="text/javascript">
function compute(){
var quant=new Array();
var price=new Array();
var stotal=new Array();
var tbox=new Array();
var elemlent=document.x.elements.length;
var dib=elemlent /3;
for(var i=0; i<dib; i++)
{
quant[i] = document.x.elements['qty[i]'].value;
price[i] = document.x.elements['cost[i]'].value;
stotal[i]= quant[i] * price[i];
tbox[i] = document.x.elements['subtotal[i]'];
if (tbox[i])
{
tbox[i].value = stotal[i];
}
}
}
</script>
<body>
<table border="1">
<form name="x">
<th>QTY</th>
<th>COST</th>
<th>SUBTOTAL</th>
<td>+</th>
<?php
for($i=0;$i<2;$i++){
?>
<tr>
<td><input type="text" name="qty[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="cost[<?php echo $i; ?>]" value=""/></td>
<td><input type="text" name="subtotal[<?php echo $i; ?>]" value=""/></td>
<td><img src="add-icon.png" onmouseover="compute();"></td>
</tr>
<?php } ?>
</form>
</table>
</body>
I just can't seem to make this work when I add for loops.
Can you see what's wrong with my code?
Change:
['qty[i]']
to:
['qty[' + i + ']']
and similar for the other ones to make the above work. I suggest you change <input> elements to provide the id, something along these lines:
<input type="text" id="qty[<?php echo $i; ?>]" name="qty[<?php echo $i; ?>]" value=""/>
Then, instead of:
quant[i] = document.x.elements['qty[i]'].value;
use:
quant[i] = document.getElementById(['qty[' + i + ']']).value;
Note also that you are going to get a string, so I suppose you'd like to use parseInt and/or parseFloat:
http://www.w3schools.com/jsref/jsref_parseInt.asp
http://www.w3schools.com/jsref/jsref_parseFloat.asp
i.e. something like this:
quant[i] = parseFloat(document.getElementById(['qty[' + i + ']']).value);
Note, also, that you may want to consider checking for errors (e.g. if someone enters "qqaacc" in price field instead of "123.45").

Categories

Resources