Math.round() is not working in my JavaScript? - javascript

Am very new to php and JavaScript. Am trying to round the value that i get from php and store that value in a JavaScript Variable and display it in a text input.
Below is my code:>
This is my order_stack.php file
<div class="order Page">
<h1>Order Entry</h1>
<form name="orderEntry" action="process_stack.php" method="post" >
<table>
<tr>
<th>
<label for="QUNTY">Quantity: </label>
</th>
<td>
<input name="quantity" type="text" id="QUNTY">
</td>
</tr>
<tr>
<th>
<label for="APW">Approx. PCS Weight: </label>
</th>
<td>
<input name="approxPcsWeight" type="text" id="APW">
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</div>
This is my process_stack.php file
<?php
$quantity = $_POST["quantity"];
$ApxPCW = $_POST["approxPcsWeight"];
$quantity1 = $_REQUEST["quantity"];
$ApxPCW1 = $_REQUEST["approxPcsWeight"];
$knittingLT = ($quantity1 * $ApxPCW1) / 200;
?>
<fieldset class="new">
<legend>Entry Tracking Details</legend>
<p>
<table>
<tr>
<th>
<label for ="QTY">Quantity: </label>
</th>
<td>
<input name="quantity" type="text" readonly="readonly" id ="QTY" value=<?php echo $quantity?>>
</td>
</tr>
<tr>
<th>
<label for ="APW">Approximate PCS Weight: </label>
</th>
<td>
<input name="Approx_PCS_weight" type="text" readonly="readonly" id="APW" value=<?php echo $ApxPCW?>>
</td>
</tr>
<tr>
<th>
<label for = "KLT">Knitting Lead Time: </label>
</th>
<td>
<input name="Knitting_Lead_time" type="text" id ="KLT" >
<script>
var data = "<?php echo $knittingLT; ?>";
var roundedData = Math.round('data');
document.getElementById('KLT').value = roundedData;
</script>
</td>
</tr>
</table>
</p>
</fieldset>
What am doing here is, i multiply both Quantity and Approx. PCS Weight and divide the obtained value by 200. Then i store the value in $knittingLT.
Now in process_stack.php, i want to update the Knitting Lead Time(which is a JS variable) by taking $knittingLT(which is a php variable) and round up the data and store it in Knitting Lead Time.
When i run the files, the Knitting Lead Time field is empty.
Is my approach toward this problem is wrong?
Kindly help me to solve this issue.
Thanks.

I guess the problem is that you are trying to round the string literal 'data'.
Instead of
var roundedData = Math.round('data');
write
var roundedData = Math.round(data);

You are rounding a string with the word 'data'.
Instead of Math.round('data'); use Math.round(data);.
Also, you are making the PHP outcome a string by putting it between quotes. Although you can use Math.round on a string, it is better to make it a number to prevent confusion.
20 == '20' // true
20 === '20' // false
Try:
var data = <?php echo $knittingLT; ?>;
<script>
var data = <?php echo $knittingLT; ?>;
var roundedData = Math.round(data);
document.getElementById('KLT').value = roundedData;
</script>

Change Math.round('data'); to Math.round(data);
Math.round() expect a number not a string.

Try this
var roundedData = Math.round(data); //edited this line 'data' to data
document.getElementById('KLT').value = roundedData;

Related

How do i Fix this NaN

whenever i call for the inputs made inside the table they end being NaN and it then cause all of my code to crash please check out the image attached to this post to get a full picture of what i am talking about, I even went forward to do more and when I call for the input made for user for calculations it gave the html input element instead of the inputted values the user made
whenever i call for the input in the table i get what you see
let $unitload1 = document.getElementById("unitload1");
let $unitload2 = document.getElementById("unitload2");
let $unitload111 = parseInt($unitload1.value);
let $unitload222 = parseInt($unitload2.value);
//grade tables
// const $selectedGrade;
let grading1 = document.getElementById("courseGrade1");
let grading2 = document.getElementById("courseGrade2");
const $gpa = document.getElementById("gpaprint");
const check1 = "yes ooo";
console.log($unitload111, $unitload222);
<table>
<tr>
<td>
<div contenteditable="true">cve 445</div>
</td>
<td>
<div contenteditable="true">RAW MATERIALS</div>
</td>
<td><input type="number" id="unitload1" value="1"/></td>
<td><input type="number" id="courseGrade1" value="1" /></td>
</tr>
<tr>
<td>
<div contenteditable="true">cve 945</div>
</td>
<td>
<div contenteditable="true">RAW MATERIALS</div>
</td>
<td><input type="number" id="unitload2" value="2"/></td>
<td><input type="text" id="courseGrade2" value="2" /></td>
</tr>
</table>
You can try to use Number in place of parseInt to cast the String value to number. Example:
let $unitload222 = Number($unitload2.value);

Only the button in the first row is working in html table using javascript

I have an add button in a table for every row, which when clicked should print the price in the price column by multiplying the quantity entered by the user with the price of the product. But it is only working for the 1st row. How do I make it work?
<div class="container">
<div class="row">
<div class="bg-white">
<form method="POST">
<table class="table table-responsive" id="myTable">
<tr>
<th class="text-center">Item</th>
<th class="text-center">Qty</th>
<th></th>
<th class="text-center">Price</th>
<th class="text-center"></th>
</tr>
<body>
<?php
$i = 1;
foreach($_SESSION['cart'] as $name => $array){
$price = "select item_name, Item_price from item where item_name='$array'";
$result = mysqli_query($conn, $price);
while($rows = mysqli_fetch_array($result)){
$name = $rows['item_name'];
$pr = $rows['Item_price'];
?>
<tr>
<td class="text-center"><?php echo $name;?></td>
<td><input class="form-control" type="text" id="qty" style="width: 40px" name="ss"></td>
<td><button type="button" class="btn btn-success" onclick="values()">add</button></td>
<script type="text/javascript">
function values() {
var n1, n2, final;
n1 = parseFloat(document.getElementById('qty').value);
n2 = parseFloat(<?php echo $pr ?>);
final = n1*n2;
alert(final);
document.getElementById('qty').value = n1;
document.getElementById('val') = final;
}
</script>
<td id="val"></td>
<td><button type="button" name="remove" class="btn btn- danger btn_remove">X</button></td>
</tr>
<?php
}
$i++;
}
?>
</body>
</table>
</form>
</div>
</div>
You should first and foremost use prepared statements as mentioned in the comments. Make it a habit. Do it every time. It is important. And correct the tag issue.
You need to know that the function values is re-defined at every iteration of the loop, so all calculations are using the price of the last item. You should define the function exactly once. You should consider changing it to accept arguments, eg price and name. It will become clear why as you read on.
You could make the id's unique for each qty and val by adding the "name". Instead of
<input class="form-control" type="text" id="qty" ...
try something like
<input class="form-control" type="text" id="<?php echo $name.'_qty'; ?>" ....
And something similar for the val id.
Now, have the onclick take arguments, so instead of onclick="values()" when the button is created, something like onclick="values(<?php echo '\''.$name.'\','.$pr; ?>)" [all the ticks and \ are to quote the name, maybe there's a better way!].
The (one) values function can take the two arguments (function values(name,price) {), and it can "construct" the ids something like this
n1 = parseFloat(document.getElementById(name + '_qty').value);
The code I've supplied is sample only and not guaranteed syntax error free. You have a lot of typing and testing and retyping and retesting ahead of you. Slow and steady......

How will i able to add this two numbers using javascript

I have two number that calculates the amount and vat amount using JavaScript. Now how will I be able to do this?
<tr>
<th>Amount: </th>
<td><input id="amount" type="text" name="amount" class="form-control" required />
</td>
</tr>
<tr>
<th>VAT 20% Amt: </th>
<td>
<input id="vatAmt" type="text" name="vatAmount" class="form-control" />
</td>
</tr>
<tr>
<th>Total Amount: </th>
<td>
<span id="totalAmount"></span>
</td>
</tr>
then the amount due
<div class="col-md-6" >
<h3>Amount Due: £ <span id="amountValue"></span></h3>
</div>
My JavaScript code is below:
$("#amount").keyup(function () {
var value = $(this).val();
$("#amountValue").text(value);
});
$("#vatAmt").keyup(function () {
var valueVat = $(this).val();
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
Can someone help me figured this thing out? Any help is muchly appreciated. TIA
value isn't defined in your second keyup handler. You need to define it:
$("#vatAmt").keyup(function () {
var value = $("#amount").val(); // <--- here
var valueVat = $(this).val();
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
When you define a variable inside a function, it's only available within that function. Another option could be to define it globally, but I generally prefer keeping scope limited to only where you need it. Within your keyup handler for #varAmt you need two values, so you would have two calls to .val() to get two values.
Note: It's possible you may also want to use parseInt or something similar to perform your addition:
$("#vatAmt").keyup(function () {
var value = parseInt($("#amount").val()); // <--- here
var valueVat = parseInt($(this).val()); // <--- and here
var sum = value + valueVat;
$("#totalAmount").text(sum);
}).keyup();
JavaScript is pretty forgiving about types, but sometimes bugs can creep in if you rely on that. And .val() returns a string because the input is text, even if that text happens to be numeric characters.
This will do
<tr>
<th>Amount: </th>
<td><input id="amount" type="number" name="amount" class="form-control" required />
</td>
</tr>
<tr>
<th>VAT 20% Amt: </th>
<td>
<input id="vatAmt" type="number" name="vatAmount" class="form-control" />
</td>
</tr>
<tr>
<th>Total Amount: </th>
<td>
<span id="totalAmount"></span>
</td>
</tr>
<div class="col-md-6">
<h3>Amount Due: £ <span id="amountValue"></span></h3>
</div>
var value;
$("#amount").keyup(function() {
value = $(this).val();
$("#amountValue").text(value);
})
$("#vatAmt").keyup(function() {
var valueVat = $(this).val();
var sum = Number(value) + Number(valueVat);
$("#totalAmount").text(sum);
}).keyup();

Using Jquery Keyup function to pass variable from one input field to another

I am trying to autopopulate an input field (location-name) with the value entered in another field (location-address). I have looked online everywhere and managed to make the JS snippet work on a straightforward example, but for some reason this is not working with the following php code.
Just to clarify, I would like the value entered in "location-address to be passed to "location-name".
<script>
$('#location-address')
.keyup(function() {
var value = $(this).val();
$('#location-name').text(value);
})
.keyup();
</script>
<tr class="em-location-data-name">
<th style="padding-top: 14px;">
<?php _e ( 'Event unique identifier:', 'dbem' )?>
</th>
<td>
<input id="location-name" type="text" name="location_name" />
</td>
</tr>
<tr class="em-location-data-address">
<th style="padding-top: 14px;">
<?php _e ( 'Address:', 'dbem' )?> </th>
<td>
<input id="location-address" type="text" name="location_address" value="<?php echo esc_attr($EM_Location->location_address, ENT_QUOTES); ; ?>" />
</td>
</tr>
Firstly your code needs to be placed in a document.ready handler. Secondly, you need to use val() not text() to set the value of an input field.
$(function() {
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val(value);
}).keyup();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="em-location-data-name">
<th style="padding-top: 14px;">
<?php _e ( 'Event unique identifier:', 'dbem' )?>
</th>
<td>
<input id="location-name" type="text" name="location_name" />
</td>
</tr>
<tr class="em-location-data-address">
<th style="padding-top: 14px;">
<? php _e( 'Address:', 'dbem') ?>
</th>
<td>
<input id="location-address" type="text" name="location_address" value="<?php echo esc_attr($EM_Location->location_address, ENT_QUOTES); ; ?>" />
</td>
</tr>
</table>
You need to wrap your jQuery code in $(document).ready(); so that jQuery binds all HTML elements.
Corrected code:
<script>
$(document).ready(function(){
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val( value );
});
}).keyup();
</script>
Use this
<script>
$(document).ready(function(){
$('#location-address').keyup(function() {
var value = $(this).val();
$('#location-name').val( value );
});
});
</script>

Take checkbox values and add them to text input

I have a text input that holds email addresses, each one gets separated by a , to indicate a breaking point for php.
<input type="text" name="to" class="form-control">
Rather than having to retype every email address every time, I have came up with a table that holds all my email addresses and allows me to select the ones I want to send emails to.
<table class="table">
<thead>
<tr>
<th>
</th>
<th>
Client
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
<?php foreach($clients as $client): ?>
<tr>
<td>
<input id="toList" name="to" type="checkbox">
</td>
<td>
<?php echo $client->name.' '.$client->last_name; ?>
</td>
<td>
<?php echo $client->email; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Add To Email
Now, I just need to figure out a way, using javascript that when the add button is clicked javascript adds all the values of all the checked checkboxes to the to input field dividing each one by ,.
hi i have created a jsfiddle for you..
code:-
$(document).ready(function() {
$("#btn").click(function() {
var checkedEmails = $("input[name=to]:checked").closest("tr");
var data = [];
$.each(checkedEmails, function() {
data.push($.trim($(this).find("td:eq(2)").text()));
});
var str = data.join(",");
$("#txt").val(str);
});
});
working example:-
http://jsfiddle.net/XUjAH/1102/
thanks
Change your checkbox to look like this
<input id="toList<?php echo $counter; ?>" class="email-check-box" name="to" type="checkbox" value="<?php echo $client->email;?>">
Javascript part
$(".add").on("click", function() {
$('.email-check-box').each(function () {
var current= (this.checked ? $(this).val() : "");
if(current) {
$(".form-control").val(
$(".form-control").val() + current+ ","
);
}
});
});

Categories

Resources