I'm trying to achive an auto calculation in JQuery, basicly there are two input fields qty times by unitPrice and the
result should display at dealPrice
input box, the problem I'm facing is the inputs are in a while loop I need to differentiate each of it's ID's so I'm
using ". $row1['prid'] . " in all three classes. There are NO errors but somehow I can NOT get it to work.
$prid = array();
while ($row1 = mysql_fetch_array($result1,MYSQL_ASSOC){
$prid[] = $row1['prid'];
echo "<tr>
<td>".$row1["prdesc"]."</td>
<td><input type='text' class='qty". $row1['prid'] . "' name='epid_qty_". $row1['prid'] ."' value='". $row1['qty'] . "'></td>
<td><input type='text' class='unitPrice". $row1['prid'] . "' name='epid_unitprice_". $row1['unitprice'] ."' value='". $row1['unitprice'] . "'></td>
<td><input type='text' class='dealPrice". $row1['prid'] . "' name='epid_drp_". $row1['prid'] . "' value='". $row1['deal_reg_price'] . "'> </td>";
}
$(document).ready(function(){
var arr = <?php echo '["' . implode('", "', $prid) . '"]' ?>;
var pid = [];
for (var i = 0; i < arr.length; i++) {
pid[i] = arr[i];
}
console.log(pid);
$('input[class="unitPrice'+ pid +'"]').keyup(function()
{
var a = $('input[class="qty'+ pid +'"]').val();
var b = $(this).val();
$('input[class="dealPrice'+ pid +'"]').val(parseInt( a * b));
});
});
Console output of pid;
{["27", "20", "19", ...]}
Your main issue here is that you are setting the pid variable as an array and then trying to use it as if it is not.
To make your code logical, you need to put a for loop around the part of the code where you specify the key-up function. Like this:
for(var i = 0; i < pid.length; i++) {
var pidNo = pid[i];
$('input[class="unitPrice'+ pidNo +'"]').keyup(function(){
var a = $('input[class="qty'+ pidNo +'"]');
var b = $(this).val();
$('input[class="dealPrice'+ pidNo +'"]').val(parseInt( a.val() * b));
});
}
Related
Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!
I created a little script which allows users to shadow some input values from other inputs. The JavaScript part is working fine, but now when I'm trying to send the form, it doesn't send it, saying that the field the value is copied to is empty. What's the problem here? Thanks!
$(document).ready(function()
{
$(":text").blur(function()
{
var input = $(this);
var id = input.attr("id");
var fieldname = "#".concat(id);
for (i = 0; i < fields.length; i++)
{
if (fields[i][4] == id)
{
var boxname = "#copy_".concat(fields[i][0]);
if ($(boxname).prop("checked"))
{
var fieldname2 = "#".concat(fields[i][0]);
$(fieldname2).val($(fieldname).val());
}
}
}
});
$(":checkbox").change(function()
{
var input = $(this);
var id = input.attr("id");
id = id.substring(id.indexOf("_") + 1, id.length);
var fieldname = "#".concat(id);
var checked = input.prop("checked");
$(fieldname).prop("disabled", checked);
var field = FindField(0, fields[FindField(0, id)][4]);
if (checked)
{
var fieldname2 = "#".concat(fields[field][0]);
$(fieldname).val($(fieldname2).val());
}
});
});
function FindField(index, value)
{
for (i = 0; i < fields.length; i++)
{
if (fields[i][index] == value) return i;
}
return -1;
}
The form (without some irrelevant stuff):
<form method="post" action="sendform.php">
<table>
<?php
foreach ($fields as $field)
{
if ($field[0] == "divider") echo('<tr><td colspan="2"><hr /></td></tr>');
else
{
switch ($field[2])
{
case FIELD_TEXT:
{
echo('<tr><td><label for="' . $field[0] . '">' . $field[1] . ': </label></td><td>');
if ($field[4] != "")
{
foreach ($fields as $field2)
{
if ($field2[0] == $field[4])
{
echo('<input type="checkbox" id="copy_' . $field[0] . '" title="Kopeeri väljalt "' . $field2[1] . '"" />');
}
}
}
echo('<input type="text" id="' . $field[0] . '" name="' . $field[0] . '" placeholder="' . $field[1] . '" /></td></tr>');
break;
}
}
}
}
?>
<tr><td colspan="2"><hr /></td></tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" value="Saada avaldus" name="saadaavaldus" />
</td>
</tr>
</table>
</form>
A sample of the fields array:
var fields = <?php echo json_encode($fields); ?>
$fields = array
(
// ID/name label/placeholder type regex field copied from
array( "saatjanimi", "Teie täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", ""),
array( "meiliaadress", "Teie meiliaadress", FIELD_TEXT, "^([\pL-.\d]+)#([\pL-.\d]+)((\.(\pL){2,63})+)$", ""),
array( "isanimi", "Lapse isa täisnimi", FIELD_TEXT, "^[-,.'\s\pL]*\pL[-,.'\s\pL]\s+[-,.'\s\pL]*\pL[-,.'\s\pL]*$", "saatjanimi")
);
I will try to be as brief and objective as possible. I'm developing a shopping cart system and for some products categories I need to create checkboxes that corresponds to the additional products that can be added for a single product and the amount of it. I have one script to display the products by category, and if category id match with the specified number id, the additional products are recovered from the database table additionals and displayed in checkboxes with their price in the row of the product that belong to that category. In my page products.php I have the following code to display my products from database:
$sql = "SELECT p.product_id, p.product_name, p.product_price,
p.category_id, c.category_name FROM products p, categories c WHERE c.category_id = p.category_id ORDER BY p.category_id, p.product_name";
$stmt = $connection->prepare($sql);
$stmt->execute();
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals ORDER BY additional_name";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
$num = $stmt->rowCount();
$category = null;
if($num>0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if($category != $category_id)
{
if(!is_null($category)) { echo "</table>"; }
echo "<h1>{$category_name}</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>QUANTITY</th>";
if($category_id == 1) echo" <th>ADDITIONALS</th>";
echo "</tr>";
$category = $category_id;
}
echo "
<tr>
<td>
<div class='product-id' style='display: none'>{$product_id}</div>
<div class='product-name'>{$product_name}</div></td>
<td>${$product_price}
</td>
<td>
<input type='number' name='quantity' value='1' min='1' max='20'/>
</td>";
if($category_id == 1)
{
echo "<td>";
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
echo "
<input type='checkbox' name='acr[]' value='{$additional_id}'/>{$additional_name} - ${$additional_price} <input type='number' name='quantity_acr[]' value='1' min='1' max='5'/><br/>
";
}
echo "</td>";
}
echo "<td>
<form class='add'>
<button type='submit'>Add</button>
</form>
</td>
</tr>";
}
echo "</table>";
}
With this code, my output is something like this:
http://i.imgur.com/1mEPljR.png
The category id 1 corresponds to the Food category so, the additionals column will be displayed.
I use this jQuery code to get the values and add them to a Query String:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity;
return false;
});
});
And here is my problem. I have no idea of how to store the additional selected checkboxes products and their respective quantities in the Query String too! In add_to_cart.php I have the following code to get the variables from Query String, compare them in database and add the product to the SESSION:
if (isset($_GET['product_id']) && $_GET['product_id'] != "")
{
if(isset($_SESSION['cart']))
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
else
{
$product_id_session = 0;
}
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
if($quantity <= 0 || $quantity > 20)
{
header('Location: products.php?action=invalidquantity&product_name=' . $product_name);
}
else if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity
);
}
$_SESSION['cart'][$product_id_session] = $columns;
header('Location: products.php?action=added&product_name=' . $product_name);
}
}
else
{
redirect_to("products.php");
}
}
I need to do the same with the selected checkboxes! Compare them in database with additional_id and insert the name and price of them in the SESSION in the respective product array, but I do not know how to do this. I hope you understood what I want to do. I'm trying this all day but my current knowledge does not allow me to pass beyond this point. I humbly ask someone to help me.
The name of the input field is acr[]. This means you will have a numerical array inside $_GET['acr'] assuming the submit method is GET.
So you'll have $_GET['acr'][0], $_GET['acr'][1], etc.
You can always use var_dump($_GET) to see all the input values.
It might make more sense for you to use a unique identifier inside the brackets for each product type.
For example use name acr[garlic] or acr[01234] signifying a product ID.
try this : http://jsfiddle.net/zkky5c0f/
$(document).ready(function(){
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
alert(allCheckbox);
});
In your code it would be like:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity + "&checkbox=" + allCheckbox;
return false;
});
});
Then in PHP you can simply explode the string over -
example :
$checkbox = explode($_GET['checkbox']);
hope this helps :)
So I'm trying to create a weekly calendar.
I coded a loop in javascript creating the empty table and then afterwards modified the innerHTML of the appropriate td's from values taken from an SQL table using php and javascript.
My problem is that when I set the rowspan of the specific td instead of merging with the next td's it is moving them to the end of my table. If I have 2 more reputation points i will post pictures to show my problem.
Here is my code if you want to take a look at it
// Declare usefull information about the database and host
$mysql_host = "-host info-";
$mysql_database = "-database info-";
$mysql_user = "user";
$mysql_password = "pass";
// open the connection
$link = mysql_connect($mysql_host,$mysql_user, $mysql_password, $mysql_database);
// connect to the database
mysql_select_db($mysql_database, $link) or die('database not selected'. mysql_error());
// Select * from the table created in the database
$result = mysql_query("SELECT * FROM Appointment;")
or die("Could not query:" . mysql_error());
echo "<script type='text/javascript' > "
. "var hours = new Array('9:00','9:30','10:00','10:30','11:00','11:30', "
. "'12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30');"
. ""
. "var days = new Array('Mon','Tue','Wed','Thu','Fri','Sat');"
. ""
. "for ( i = 0; i < 14 ; i++ ) "
. "{"
. "document.write('<tr id='+hours[i]+':00'+'>');"
. "document.write('<th>'+ hours[i]+'</th> '); "
." for ( k = 0 ; k < 6; k++)"
."{"
. "document.write('<td id='+days[k] +'> </td>'); "
. "}"
. "document.write('</tr>');"
."}"
. " </script> ";
while( $row = mysql_fetch_array( $result ))
{
$timestamp = strtotime($row['Date']);
$day = date('D', $timestamp);
$from = $row['StartTime'];
$to = $row['EndTime'];
$rowspan = determinRowSpanBetween($from,$to);
echo "<script type='text/javascript'> "
. " var divToAddTo = GetElementInsideContainer('".$from."','".$day."');"
. "divToAddTo.className = 'busy';"
. "divToAddTo.rowspan='".$rowspan."';"
. "divToAddTo.innerHTML='Something to do';"
. "function GetElementInsideContainer(containerID, childID) {"
. " var elm = {};"
. " var elms = document.getElementById(containerID).getElementsByTagName('*');"
. " for (var i = 0; i < elms.length; i++) {"
. " if (elms[i].id === childID) {"
. " elm = elms[i];"
. " break;"
. " }"
. "}"
. "return elm;"
. "}"
. " </script>" ;
}
the function determinRowSpanBetween is created later on in the code.
Having a rowspan > 1 in a td that is only supposed to take up one space (i.e. one that is not merged with other td's) will cause a whole bunch of errors. Make sure you account for every row you add to rowspan.
I have a website where users contribute with content. The content takes form of tables, where every td element is of equal height and width. The different pieces of content have different number of rows and columns. I want to stack these elements in an infinite-scroll webpage. ATM I'm doing this: I construct a table, in it a tr. I load element by element inside tds and count their number of columns. When a certain threshold has been reached, i break the tr and start a new tr. This makes the content elements border eachother sideways, leaving no room between each. However I also want to load the elements in such a way that there is minimal room between elements vertically. How can I do this?
Here is my code. I DO NOT expect to have it rewritten or have new code written for me. This is only to make it clearer to you what I am currently doing.
<?php
$row = 0;
$column = 0;
$maxColumns = 124;
echo "<table><tr>";
$listHandle = fopen('pieces/piecesList', 'r');
while (!feof($listHandle)) {
echo "<td>";
$filename = trim(fgets($listHandle));
$templateHandle = fopen("pieces/" . $filename, 'r');
$thisLine = fgets($templateHandle);
list($lowestX, $highestX, $lowestY, $highestY) = sscanf($thisLine, '%d %d %d %d');
//echo $lowestX . $highestX . $lowestY . $highestY;
$templateTable = "<table id=\"" . $filename . "\" title =\"" . $filename . "\">" . PHP_EOL;
$greenCells = array();
$fileLength = 0;
while (!feof($templateHandle)) {
$thisLine = fgets($templateHandle);
list($thisX, $thisY) = sscanf($thisLine, '%d %d');
$carrier = $thisX . " " . $thisY;
array_push($greenCells, $carrier);
$fileLength++;
}
for ($y = $lowestY; $y <= $highestY; $y++) {
// echo "inside for loop Y \n";
$templateTable = $templateTable . "<tr>" . PHP_EOL;
for ($x = $lowestX; $x <= $highestX; $x++) {
// echo $y . $x;
$templateTable = $templateTable . "<td";
$coordinateExists = FALSE;
for ($i = 0; $i < $fileLength; $i++) {
if ($greenCells[$i] == $x . " " . $y) {
$coordinateExists = TRUE;
break;
}
}
if ($coordinateExists) {
$templateTable = $templateTable . " class=\"green";
if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " markerdot";
}
$templateTable = $templateTable . "\"";
} else if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " class=\"markerdot\"";
}
$templateTable = $templateTable . " x='" . $x . "' y='" . $y . "'>";
$templateTable = $templateTable . "</td>" . PHP_EOL;
}
$templateTable = $templateTable . "</tr>" . PHP_EOL;
}
$templateTable = $templateTable . "</table> </td>";
if ($column == 0) {
$tallestTemplateHeight = $highestY - $lowestY;
} else if (($highestY - $lowestY) > $tallestTemplateHeight) {
$tallestTemplateHeight = $highestY - $lowestY;
}
echo $templateTable;
$column += $highestX - $lowestX;
if ($column >= $maxColumns) {
$row += $tallestTemplateHeight;
echo "</tr></table><table><tr>";
}
}
fclose($listHandle);
?>
</div>
PS: I am open to discarding my current setup entirely.
I'll throw this out as an idea - FIDDLE
It uses divs instead of a table, and by playing with the loops, width, etc, you can adjust it as you see fit.
Everything fits together edge to edge.
JS
var counter = 0;
var numdivs = 8;
$('#clickme').click(function(){
for(var i=1; i < 50; ++i)
{
$("<div class='standarddiv'>X</div>").appendTo('.holder');
counter = counter + 1;
if(counter==numdivs)
{
$("<div class='clearboth'></div>").appendTo('.holder');
counter = 0;
}
}
});