Dynamic Rows Form Submit - javascript

I have a decent sized form on my website which has an insert row button at the bottom, this adds rows to the bottom of the form to which I can also click the corresponding delete button to delete that single row to.
Screenshot of the bottom of the form
Now, the issue arises when I click the "Send" button. If I have added a few rows to the form and then click the "Send" button, the rows disappear from the form and so do their values. I want it so once I've added the rows and click the send button, the form keeps its state properly and keeps the rows that I previously added.
HTML Code can be found here:
<form name="contact" action="request-a-quote.php" method="POST">
<table class="form">
<thead>
<?php if (isset($form_error_message)) { echo $form_error_message; } ?>
<tr>
<th colspan="3">Company Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Company Name *</th>
<td colspan="2"><input name="company_name" type="text" <?php if ($error_company_name=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Company Name"'; } ?> maxlength="45" value="
<?php if (isset($company_name)) echo $company_name; ?>"></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Contact Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Contact person name *</th>
<td colspan="2"><input name="contact_person_name" type="text" <?php if ($error_contact_person_name=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Name"'; } ?> maxlength="45" value="
<?php if (isset($contact_person_name)) echo $contact_person_name; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Contact person e-mail *</th>
<td colspan="2"><input name="contact_person_email" type="email" <?php if ($error_contact_person_email=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Email"'; } ?> size="40" value="
<?php if (isset($contact_person_email)) echo $contact_person_email; ?>" /></td>
</tr>
<tr>
<th class="desktop_only">Contact address *</th>
<td colspan="2"><input name="contact_address" type="text" <?php if ($error_contact_address=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Address"'; } ?> maxlength="45" value="
<?php if (isset($contact_address)) echo $contact_address; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Contact person phone *</th>
<td colspan="2"><input name="contact_person_phone" type="text" <?php if ($error_contact_person_phone=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Contact Person Phone"'; } ?> maxlength="45" value="
<?php if (isset($contact_person_phone)) echo $contact_person_phone; ?>"></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Boiler Information</th>
</tr>
</thead>
<tbody>
<tr>
<th class="desktop_only">Boiler brand / manufacturer *</th>
<td colspan="2"><input name="boiler_brand_manufacturer" type="text" <?php if ($error_boiler_brand_manufacturer=='Y' ) { echo 'class="error_on_field"'; } ?>
<?php if ($detect->isMobile()) { echo 'placeholder="Boiler brand / Manufacturer"'; } ?> maxlength="45" value="
<?php if (isset($boiler_brand_manufacturer)) echo $boiler_brand_manufacturer; ?>"></td>
</tr>
<tr>
<th class="desktop_only">Average annual fuel consumption (kW or £)</th>
<td colspan="2"><input name="average_annual_fuel_consumption" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Average annual fuel consumption (kW or £)"'; } ?> size="60" value="
<?php if (isset($average_annual_fuel_consumption)) echo $average_annual_fuel_consumption; ?>" ></td>
</tr>
<tr>
<th class="desktop_only">Current cost per kW (Pence)</th>
<td colspan="2"><input name="current_cost_per_kw" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Current cost per kW (Pence)"'; } ?> size="60" value="
<?php if (isset($current_cost_per_kw)) echo $current_cost_per_kw; ?>" ></td>
</tr>
<tr>
<th>Type of fuel</th>
<td colspan="2">
<select name="type_of_fuel">
<option value="0">Please Select...</option>
<option <?php if ($type_of_fuel == "Gas") echo "selected=selected" ?>>Gas</option>
<option <?php if ($type_of_fuel == "Oil") echo "selected=selected" ?>>Oil</option>
<option <?php if ($type_of_fuel == "LPG") echo "selected=selected" ?>>LPG</option>
<option <?php if ($type_of_fuel == "Other") echo "selected=selected" ?>>Other</option>
</select>
</td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Boiler Capacity</th>
</tr>
</thead>
<tbody>
<tr>
<th>Type of boiler</th>
<td colspan="2">
<select name="type_of_boiler">
<option value="0">Please Select...</option>
<option <?php if ($type_of_boiler == "Thermostatically Controlled") echo "selected=selected" ?>>Thermostatically Controlled</option>
<option <?php if ($type_of_boiler == "CHP") echo "selected=selected" ?>>CHP</option>
<option <?php if ($type_of_boiler == "Steam") echo "selected=selected" ?>>Steam</option>
</select>
</td>
</tr>
<tr>
<th class="desktop_only">Total capacity</th>
<td colspan="2"><input name="total_capacity" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Total Capacity"'; } ?> size="60" value="
<?php if (isset($total_capacity)) echo $total_capacity; ?>" ></td>
</tr>
<tr>
<th class="desktop_only">Boiler capacity</th>
<td colspan="2"><input name="boiler_capacity" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Boiler Capacity"'; } ?> size="60" value="
<?php if (isset($boiler_capacity)) echo $boiler_capacity; ?>" ></td>
</tr>
</tbody>
<thead>
<tr>
<th colspan="3">Required Measurements (up to 4 meters)</th>
</tr>
</thead>
<tbody class="row">
<tr>
<td colspan="3" class="center">
<img src="images/required-measurements.jpg" alt="Required Measurements" />
</td>
</tr>
</tbody>
</table>
<table id="addrows">
<thead>
<tr>
<th></th>
<th>Circumference</th>
<th>Length</th>
<th></th>
</tr>
</thead>
<tbody class="row">
<tr>
<th>Measurement 1</th>
<td><input name="circumference_1" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Circumference 1"'; } ?> size="60" value="
<?php if (isset($circumference_1)) echo $circumference_1; ?>" ></td>
<td><input name="length_1" type="text" <?php if ($detect->isMobile()) { echo 'placeholder="Length 1"'; } ?> size="60" value="
<?php if (isset($length_1)) echo $length_1; ?>" ></td>
<td style="width:200px;"></td>
</tr>
</tbody>
</table>
<p><input type="button" id="insert_row" value="Insert row"></p>
<script>
$('#addrows').on('click', 'input[type="button"]', function() {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function() {
$('#addrows').append('<tr><th>Measurement 2</th><td><input type="text" class="fname" /></td><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
</script>
<table class="form">
<tr id="send_holder">
<td class="calculate" colspan="3">
<input type="submit" id="send" value="Send">
<input type="hidden" name="submitted" value="TRUE">
</td>
</tr>
</table>
</form>
PHP Code can be found here:
<?php
// Taken from http://php.net/manual/en/function.mail.php - Example #4 Sending HTML email
// PHP script triggers if SEND button has been clicked
if (isset($_POST['submitted'])) {
// Set up Fasthosts mandatory settings to enable email sending
$email_from = 'EMAIL'; // Must be an email set-up in Fasthosts, mailbox or forwarder
ini_set('SMTP','smtp.fasthosts.co.uk' );
ini_set('sendmail_from', $email_from);
$website_name = 'NAME'; // Change to the name of the website in which the form is
$form_name = 'Request a Quote'; // Change to the name of the form
// Populate PHP variables from $_POST array
$company_name = htmlentities(trim($_POST['company_name']),ENT_QUOTES,"ISO-8859-15");
$contact_person_name = htmlentities(trim($_POST['contact_person_name']),ENT_QUOTES,"ISO-8859-15");
$contact_person_email = htmlentities(trim($_POST['contact_person_email']),ENT_QUOTES,"ISO-8859-15");
$contact_address = htmlentities(trim($_POST['contact_address']),ENT_QUOTES,"ISO-8859-15");
$contact_person_phone = htmlentities(trim($_POST['contact_person_phone']),ENT_QUOTES,"ISO-8859-15");
$boiler_brand_manufacturer = htmlentities(trim($_POST['boiler_brand_manufacturer']),ENT_QUOTES,"ISO-8859-15");
$average_annual_fuel_consumption = htmlentities(trim($_POST['average_annual_fuel_consumption']),ENT_QUOTES,"ISO-8859-15");
$current_cost_per_kw = htmlentities(trim($_POST['current_cost_per_kw']),ENT_QUOTES,"ISO-8859-15");
$type_of_fuel = htmlentities(trim($_POST['type_of_fuel']),ENT_QUOTES,"ISO-8859-15");
$type_of_boiler = htmlentities(trim($_POST['type_of_boiler']),ENT_QUOTES,"ISO-8859-15");
$total_capacity = htmlentities(trim($_POST['total_capacity']),ENT_QUOTES,"ISO-8859-15");
$boiler_capacity = htmlentities(trim($_POST['boiler_capacity']),ENT_QUOTES,"ISO-8859-15");
$circumference_1 = htmlentities(trim($_POST['circumference_1']),ENT_QUOTES,"ISO-8859-15");
$length_1 = htmlentities(trim($_POST['length_1']),ENT_QUOTES,"ISO-8859-15");
// Check for errors and update error variables, e.g. $error_on_name, etc.
if (empty($company_name)) { $error_company_name = 'Y'; }
if (empty($contact_person_name)) { $error_contact_person_name = 'Y'; }
if (empty($contact_person_email)) { $error_contact_person_email = 'Y'; }
if (empty($contact_address)) { $error_contact_address = 'Y'; }
if (empty($contact_person_phone)) { $error_contact_person_phone = 'Y'; }
if (empty($boiler_brand_manufacturer)) { $error_boiler_brand_manufacturer = 'Y'; }
$errors_exist = $error_company_name.$error_contact_person_name.$error_contact_person_email.$error_contact_address.$error_contact_person_phone.$error_boiler_brand_manufacturer;
// No errors exist - Set up and send emails and redirect
if (!empty($errors_exist)) {
$form_error_message = '<tr><td colspan="2"><p id="form_error_message">There are a few pieces of information that we need from you before this form comes through to us. They are highlighted below in red, so please fill those in again and click the <strong>Submit</strong> button again.</p></td></tr>';
// Else, i.e. if $errors array is empty
} else {
// Set up email recipient(s)
$to1 = $contact_person_email; // First email is sent to the person who submitted the form; $email
$to2 = 'email_address'; // Second email is sent to the website owner; change this to the relevant email address
// Set up email subject(s)
$subject1 = 'Thanks for your submission - '.$website_name.' - '.$form_name.' form'; // Do not change
$subject2 = 'Website submission - '.$website_name.' - '.$form_name.' form'; // Do not change
// Set up email message(s)
$message1 = '
<div style="font-family: arial, tahoma, sans serif; font-size: small; color: #666;">
<p>Hi '.$contact_person_name.',</p>
<p>Thanks for completing our '.$form_name.' form on the '.$website_name.' website. We\'ll be in touch as soon as we can!</p>
<p>With kind regards<br />'.$website_name.'</p>
</div>';
$message2 = '
<div style="font-family: arial, tahoma, sans serif; font-size: small; color: #666;">
<p>The following submission has been made via the '.$form_name.' form:</p>
<h2>Company Information</h2>
<p>Company Name: '.$company_name.'</p>
<h2>Contact Information</h2>
<p>
Contact Person Name: '.$contact_person_name.'
<br />Contact Person Email: '.$contact_person_email.'
<br />Contact Address: '.$contact_address.'
<br />Contact Person Phone: '.$contact_person_phone.'
</p>
<h2>Boiler Information</h2>
<p>
Boiler Brand/Manufacturer: '.$boiler_brand_manufacturer.'
<br />Average Annual Fuel Consumption: '.$average_annual_fuel_consumption.'
<br />Current Cost per kW: '.$current_cost_per_kw.'
<br />Type of Fuel: '.$type_of_fuel.'
</p>
<h2>Boiler Capacity</h2>
<p>
Type of Boiler: '.$type_of_boiler.'
<br />Total Capacity: '.$total_capacity.'
<br />Boiler Capacity: '.$boiler_capacity.'
</p>
</div>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers can be set here; Change From to website owner
$headers .= 'From: NAME <' . $email_from . '>' . "\r\n";
// Send emails
mail($to1, $subject1, $message1, $headers);
mail($to2, $subject2, $message2, $headers);
// Errors exist - populate $form_error_message ready for output to browser
}
} // END-OF-IF (isset($_POST['submitted']))
// Stage M3. Add <p> to end of $form_error_message
$form_error_message = $form_error_message.'</p>';
?>

Once you're doing a form submit (instead of an Ajax call) it's pretty easy.
In your form:
<input type="text" name="measure[]" value="This input is fixed">
Each time you add a new input (from the group "measure") it should has the same name as an array: name="measure[]" like the input above.
Then in PHP you just need to run into this array to get all fields.
<?php
$total_elements = count($_POST['measure']);
for ( $i=0;$i<$total_elements;++$i ) {
echo $_POST['measure'][$i];
}
?>
Hope it helps.

Related

How to update data from dynamically created table to database in php

I have create a table using php dynamically. But i need to update some of the cell value depending on user input. But i can't figure out how to do that. my codes are given below.
I have found a way to make names an array is to use [] in names attribute from stackoverflow. but it didn't work for me.If i echo $_POST['std_name'] in while loop or outside of loop only the last row of student name is counted. Please Someone help. I am stuck here for 3 days.
<form action="" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Student Father Name</th>
<th>Student Mother Name</th>
<th>Student Parents Mobile Number</th>
<th>Student Mobile Number</th>
<th>Student Batch Name</th>
<th>Student College Name</th>
<th>Student Gender</th>
<th>Student Picture</th>
<th>Student Admit Date</th>
<th>January</th>
<th>February</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
<tr>
<?php
$host="localhost";
$username="root";
$password="";
$db="paragon_first_year";
$qry="select * from `student_info`";
$con=mysqli_connect($host,$username,$password);
mysqli_select_db($con,$db);
$res=mysqli_query($con,$qry);
if(mysqli_num_rows($res)>0){
while($dt=mysqli_fetch_array($res)){?>
<td><input type="text" name="std_id[]" value="<?php echo $dt['std_id']?>"></td>
<td><input type="text" name="std_name[]" value="<?php echo $dt['std_name']?>"></td>
<td><input type="text" name="std_father_name[]" value="<?php echo $dt['std_father_name']?>"></td>
<td><input type="text" name="std_mother_name[]" value="<?php echo $dt['std_mother_name']?>"></td>
<td><input type="text" name="std_parent_mob[]" value="<?php echo $dt['std_parents_mob_no']?>"></td>
<td><input type="text" name="std_mob[]" value="<?php echo $dt['std_mob_no']?>"></td>
<td><?php echo $dt['std_batch_name'] ?></td>
<td><?php echo $dt['std_college_name'] ?></td>
<td><?php echo $dt['std_gender'] ?></td>
<td><img style="height:100px;width:100px;" src="uploadImage/<?php echo $dt['std_name']."_".$dt['std_pic'] ?>" alt=""></td>
<td><?php echo $dt['std_admit_date'] ?></td>
<td><input type="text" name="jan[]" value="<?php echo $dt['january']?>"></td>
<td><input type="text" name="feb[]" value="<?php echo $dt['february']?>"></td>
<td><input type="text" name="mar[]" value="<?php echo $dt['march']?>"></td>
<td><input type="text" name="apr[]" value="<?php echo $dt['april']?>"></td>
<td><input type="text" name="may[]" value="<?php echo $dt['may']?>"></td>
<td><input type="text" name="jun[]" value="<?php echo $dt['june']?>"></td>
<td><input type="text" name="jul[]" value="<?php echo $dt['july']?>"></td>
<td><input type="text" name="aug[]" value="<?php echo $dt['august']?>"></td>
<td><input type="text" name="sep[]" value="<?php echo $dt['september']?>"></td>
<td><input type="text" name="oct[]" value="<?php echo $dt['october']?>"></td>
<td><input type="text" name="nov[]" value="<?php echo $dt['november']?>"></td>
<td><input type="text" name="dec[]" value="<?php echo $dt['december']?>"></td>
</tr><?php
}
}
?>
</table>
<center>
<input type="submit" name="submit" value="Update Data">
</center>
</form>
</body>
my table is showing nicely
hope someone help. Thanks in advance.
You can use array keys to pass information. In this example, the first key is the database primary key, and the second key is the variable name.
The resulting array would look something like this:
$row[123][std_name] = 'joe';
$row[123][std_father_name] = 'bob';
... etc
$row[124][std_name] = 'sally';
$row[124][std_father_name] = 'john';
...etc
Then, as you iterate through the rows, you get the key (123) to use to update the database, as in where std_id=123.
Note: I have used prepared statements to show updating the database. This is essential. Never put variables in a query using concatenation ( i.e., "select * from table where id='$id'")
Lastly, note the structure. Start with PHP, no print or echo statements. This allows you to work with user input and then redirect. First initialize, then work with user input, then do page logic, and lastly get out of php and output the view (html)
This example is not copy and paste; it has things that need to be filled in, and probably debugged. It is merely intended to show the big picture.
<?php
// initialize
$host="localhost";
$username="root";
$password="";
$db="paragon_first_year";
$con=mysqli_connect($host,$username,$password);
// a simple wrapper to make the prepared query more manageable
// see https://phpdelusions.net/mysqli/mysqli_connect#helper
function prepared_query($mysqli, $sql, $params, $types = "")
{
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
// work with user input
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$dataRows = (array)$_POST['data'];
foreach($dataRows as $id=>$data) {
$sql = "INSERT INTO student_info SET std_name=?, std_father_name=?, " .
// etc .
"WHERE std_id=?";
$params = array(
$data['std_name'],
$data['std_father_name'],
// etc...
$id
);
// this does the prepare, bind, and execute... Yes, I could just do the
// bind and execute here, but the time savings isn't worth the trouble.
$stmt = prepared_query($con, $sql, $params);
}
// always redirect after a POST
header('Location: /path/to/next/page/or/this/page');
die;
}
// no user input; ok to use plain old query.
$qry="select * from `student_info`";
mysqli_select_db($con,$db);
$res=mysqli_query($con,$qry);
?>
<html>
...
<form action="" method="post">
<table>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Student Father Name</th>
<th>Student Mother Name</th>
<th>Student Parents Mobile Number</th>
<th>Student Mobile Number</th>
<th>Student Batch Name</th>
<th>Student College Name</th>
<th>Student Gender</th>
<th>Student Picture</th>
<th>Student Admit Date</th>
<th>January</th>
<th>February</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>June</th>
<th>July</th>
<th>August</th>
<th>September</th>
<th>October</th>
<th>November</th>
<th>December</th>
</tr>
<!-- don't need mysqli_num_rows; the while won't loop if no results -->
<?php while($dt=mysqli_fetch_array($res)): ?>
<tr>
<td><?= $dt['std_id'] ?></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_name']" value="<?= $dt['std_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_father_name']" value="<?= $dt['std_father_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mother_name']" value="<?= $dt['std_mother_name'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_parent_mob']" value="<?= $dt['std_parents_mob_no'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['std_mob']" value="<?= $dt['std_mob_no'] ?>"></td>
<td><?= $dt['std_batch_name'] ?></td>
<td><?= $dt['std_college_name'] ?></td>
<td><?= $dt['std_gender'] ?></td>
<td><img style="height:100px;width:100px;" src="uploadImage/<?= $dt['std_name']."_".$dt['std_pic'] ?>" alt=""></td>
<td><?= $dt['std_admit_date'] ?></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jan']" value="<?= $dt['january'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['feb']" value="<?= $dt['february'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['mar']" value="<?= $dt['march'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['apr']" value="<?= $dt['april'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['may']" value="<?= $dt['may'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jun']" value="<?= $dt['june'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['jul']" value="<?= $dt['july'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['aug']" value="<?= $dt['august'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['sep']" value="<?= $dt['september'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['oct']" value="<?= $dt['october'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['nov']" value="<?= $dt['november'] ?>"></td>
<td><input type="text" name="data[<?= $dt['std_id'] ?>]['dec']" value="<?= $dt['december'] ?>"></td>
<?php endwhile; ?>
</tr>
</table>
<center>
<input type="submit" name="submit" value="Update Data">
</center>
</form>
</body>

Selecting an appending ID attribute with jQuery

Why does the last 'In Stock' field replaces every other 'In Stock' field when I'm trying to place value on the quantity?
<form action="add_sales.php" method="POST">
<table class="table table-striped table-bordered table-hover results table-fixed">
<thead>
<tr>
<th class="text-center">#</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
<th>In Stock</th>
<th style="width: 20%">Quantity</th>
</tr>
<tr class="warning no-result">
<td colspan="8"><i class="fa fa-warning"></i> No Product Found</td>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM products";
$exec = mysqli_query($connection, $query);
$a = 1;
$b = 1;
while ($row = mysqli_fetch_array($exec)) {
$product_id = $row['product_id'];
$product_name = $row['product_name'];
$product_price = $row['sell_price'];
$description = $row['description'];
$product_quantity = $row['quantity'];
}
?>
<tr>
<td class="text-center"><?php echo $product_id; ?><input type="hidden" name="product_id[]" value="<?php echo $product_id; ?>"></td>
<td><?php echo $product_name; ?></td>
<td><?php echo $description; ?></td>
<td><?php echo $product_price; ?></td>
<td><input type="number" name="hehe" value="<?php echo $product_quantity; ?>" id="<?php echo "qtyResult" . $a++; ?>" disabled></td>
<td><input type="number" name="qtyBuy[]" id="<?php echo "qtyBuy" . $b++; ?>" onkeyup="updateStock(this, event)"></td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="form-group">
<input type="submit" name="addCart" value="Add Items to Cart" class="btn btn-info pull-right">
</div>
</form>
Here is my jQuery script. I think the problem is in the var inStock's value. When I change the var inStock's value to a fixed number, it's working fine.
function updateStock(obj, event) {
var inputQty = obj.value;
var inStock = "<?php echo $product_quantity; ?>";
$(obj).closest('tr').find('input[id^="qtyResult"]').val(inStock - inputQty);
}
Because $product_quantity will be set to the last value in the loop.
If you view source and look at the javascript function, you will see it reads:
function updateStock(obj, event) {
var inputQty = obj.value;
var inStock = "234"; //or whatever the last value was
$(obj).closest('tr').find('input[id^="qtyResult"]').val(inStock - inputQty);
}
As the values can change after the page has loaded (and therefor after php has quit) you should grab the current value from the dom when you need it:
function updateStock(obj, event) {
var inputQty = obj.value;
var quantityInput = $(obj).closest('tr').find('input[id^="qtyResult"]');
quantityInput.val(quantityInput.val() - inputQty);
}

I want particular cell value when i clicking on it

<?php
$con = mysql_connect('localhost','root','');
$db = mysql_select_db("demo",$con);
?>
<!doctype html>
<html>
<head>
<title>Demo</title>
<!--JAVASCRIPT -->
<script src="http://code.jquery.com/jquery-1.9.1.min.js" ></script>
<script>
$(document).ready(function(){
$("#myTable td").click(function() {
var column_num = parseInt( $(this).index() ) + 1;
var row_num = parseInt( $(this).parent().index() )+1;
//$("#result").html( "Row_num =" + row_num + " , Column_num ="+ column_num );
alert(row_num);
});
});
</script>
</head>
<body>
<!--<div id="result"> </div>-->
<table id="myTable" border="1" style="border-collapse: collapse;" cellpadding="8">
<tr>
<th>Name</th>
<th>Qty</th>
<th>Amount</th>
<th>Total</th>
</tr>
<?php
$sQ = "select * from tbl_demo";
$eQ = mysql_query($sQ);
while($fQ=mysql_fetch_array($eQ))
{
$name = $fQ['Name'];
$qty = $fQ['Qty'];
$amt = $fQ['Amount'];
//$total
$total = $fQ['Total'];
?>
<tr>
<td><input type="text" name="name" value="<?php echo $name; ?>" onchange="add($qty,$amt)"/> </td>
<td><input type="number" name="name" value="<?php echo $qty; ?>"/></td>
<td><input type="number" name="name" value="<?php echo $amt; ?>"/></td>
<td><input type="number" name="name" value="<?php echo $total; ?>"/></td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" style="padding-left:400px"> Total </td>
<td class="navigateTest"> <input type="number" name="name" value=""/> </td>
</tr>
<tr>
<td colspan="4" class="navigateTest"> <input type="button" name="submit" id="submit" value="Submit"/> </td>
</tr>
</table>
</body>
</html>
Here is my code. I get index value of particular row nd column bt i can not find value of that cell.. I tried to solve that problem bt i can not understand code which i found..which are the different ways for that??
How i get data of particular cell?????
plz redirect me at right direction...

Jquery Filter table rows by multiple checkboxes

I am trying to get a filter working for a table. What I would like is checkboxes to filter (hide) rows based on whether they're checked or not and if the value is present in the table cell. I have it somewhat working, but it will only sort one of the checkboxes. Also, if there are multiple values in the table cell being filtered, that row is hidden. Thoughts? Thank you in advance for any help. I'm really struggling with this for some reason!
Here is the code I have been using:
$("input:checkbox").click(function () {
var showAll = true;
$('tr').not('.first').hide();
$('input[type=checkbox]').each(function () {
if ($(this)[0].checked) {
showAll = false;
var status = $(this).attr('rel');
var value = $(this).val();
$('td.' + 'status' + '[rel="' + value + '"]').parent('tr').show();
}
});
if(showAll){
$('tr').show();
}
});
The markup is as follows (please excuse some messiness, its Wordpress)
<div class="grants-filter">
<h3 class="filter-title">Filter Scholarships</h3><br/>
<h3>Year of Study:</h3>
<input type="checkbox" name="chx" rel="status" value="Freshman">Freshman
<input type="checkbox" name="chx" rel="status" value="Sophmore">Sophmore
<input type="checkbox" name="chx" rel="status" value="Junior">Junior
<input type="checkbox" name="chx" rel="status" value="Senior">Senior
<br/><br/><h3>Duration:</h3>
<input type="checkbox" rel="duration" value="Summer">Summer
<input type="checkbox" rel="duration" value="Semester">Semester
<input type="checkbox" rel="duration" value="Full Year or More">Full Year or More
</div>
<div class="grants-listing">
<table border="1" id="table" class="grants-table">
<thead>
<tr class="first">
<th>Title</th>
<th>Description</th>
<th>Field</th>
<th>Duration</th>
<th>Year of Study</th>
<th>Other</th>
<th>Procedure</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<?php
$grargs = array ( 'post_type' => 'scholarship');
$grant_query = new WP_Query( $grargs );
while ( $grant_query -> have_posts() ):
$grant_query -> the_post(); ?>
<tr class="grant-detail">
<td>
<?php the_title(); ?>
</td>
<td><?php echo wp_trim_words(get_the_content(), 25 ); ?></td>
<td class="fields" rel="<?php echo get_field('fields'); ?>"><?php echo the_field('fields'); ?></td>
<td class="duration" rel="<?php echo the_field('desired_duration'); ?>"><?php echo the_field('desired_duration'); ?></td>
<td class="status" rel="<?php echo the_field('year-of-study'); ?>"><?php echo the_field('year-of-study'); ?></td>
<td class="other" rel="<?php echo the_field('other'); ?>"><?php echo the_field('other'); ?></td>
<td class="procedure" rel="<?php echo the_field('procedure'); ?>"><?php echo the_field('procedure'); ?></td>
<td class="url"><?php echo get_field('url'); ?></td>
</tr>
<?php endwhile;
wp_reset_postdata(); //reset the first query
?>
</tbody>
</table>
As I think you just are calling the first checkbox [0]
if ($(this)[0].checked) {
call all by inserting someting like
$('input[type=checkbox]').each(function () {
if (this.checked) {
console.log($(this).val());
}
});
Your code works fine, here is a simplified version
$("input:checkbox").click(function() {
var showAll = true;
$('tr').not('.first').hide();
$('input:checkbox:checked').each(function() {
showAll = false;
var status = $(this).attr('rel');
var value = $(this).val();
$('td.' + 'status' + '[rel="' + value + '"]').parent('tr').show();
});
if (showAll) {
$('tr').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="grants-filter">
<h3 class="filter-title">Filter Scholarships</h3>
<br/>
<h3>Year of Study:</h3>
<input type="checkbox" name="chx" rel="status" value="Freshman">Freshman
<input type="checkbox" name="chx" rel="status" value="Sophmore">Sophmore
<input type="checkbox" name="chx" rel="status" value="Junior">Junior
<input type="checkbox" name="chx" rel="status" value="Senior">Senior
</div>
<div class="grants-listing">
<table border="1" id="table" class="grants-table">
<thead>
<tr class="first">
<th>Title</th>
<th>Description</th>
<th>Fields</th>
<th>Status</th>
<th>Procedure</th>
</tr>
</thead>
<tbody>
<tr class="grant-detail">
<td>
Name
</td>
<td>Description</td>
<td class="fields" rel="Freshman">Freshman</td>
<td class="status" rel="Freshman">Freshman</td>
<td class="procedure" rel="Freshman">Freshman</td>
</tr>
<tr class="grant-detail">
<td>
Name
</td>
<td>Description</td>
<td class="fields" rel="Sophmore">Sopho</td>
<td class="status" rel="Sophmore">Sopho</td>
<td class="procedure" rel="Sophmore">Sopho</td>
</tr>
<tr class="grant-detail">
<td>
Name
</td>
<td>Description</td>
<td class="fields" rel="Junior">Junior</td>
<td class="status" rel="Junior">Junior</td>
<td class="procedure" rel="Junior">Junior</td>
</tr>
</tbody>
</table>

When I load my php page then submit button automatically press and page again and again loading?

I'm using wamp server php my admin sql,table created connection every thing is fine,I'm working on local host, but page again and gain loading, not move down cursor etc, submit button automatically click ?
Here is screen shot http://i.imgur.com/QC6RtAg.jpg?1
<center><form method="post">
<table border="0" cellspacing="8">
<tr>
<td><label><b>*Select Campus:</b></label></td>
<td>
<select name="city" id="city">
<option value="">-Please Select-</option>
<option value="Isb">Islamabad</option>
<option value="Abt">Abbotabad</option>
<option value="wah">Wah</option>
<option value="Atk">Attock</option>
<option value="shw">Sahiwal</option>
<option value="veh">Vehari</option>
<option value="vir">Virtual</option>
</select>
<font color="red"><?php echo #$_GET['campus'];?></font>
</td>
</tr>
<tr>
<td><label><b>*Name</b></label></td>
<td><input type="text" name="name" />
<font color="red"><?php echo #$_GET['newname'];?></font>
<td></tr>
<br/>
<tr>
<td><label><b>*Login</b></label></td>
<td><input type="text" name="logid"/>
<font color="red"><?php echo #$_GET['logname'];?></font>
<td></tr>
<br/>
<tr>
<td><label><b>*Email Address</b></label></td>
<td><input type="text"type="require" name="email"/>
<font color="red"><?php echo #$_GET['emailname'];?></font>
</td></tr>
<br/>
<tr>
<td><label><b>*Password</b></label></td>
<td><input type="password" type="require" name="pass"/>
<font color="red"><?php echo #$_GET['passname'];?></font>
</td></tr>
<br/>
<tr>
<td><label><b>*Retype Password</b></label></td>
<td><input type="password" type="require" name="rpass"/>
<font color="red"><?php echo #$_GET['rpassname'];?></font>
</td></tr>
</table>
<table border="0">
<tr id="bu">
<td ><input type="submit" id="cl" value="sign up"name="submit"/></td> </tr>
</table>
</form>
</center>
<?php
$conn = mysqli_connect('localhost', 'root' , '','example');
if(isset($_POST['submit']))<?php
{
$campus=$_POST['city'];
$name = $_POST['name'];
$u_id = $_POST['logid'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
if($campus==''){
echo
"<script>window.open('Log.php?campus=Select campus is Required','_self')
</script>";
exit();
}
if($name==''){
echo
"<script>window.open('Log.php?newname=Name is Required','_self') </script>";
exit();
if($u_id==''){
echo
"<script>window.open('Log.php?logname=User ID is Required','_self')</script>";
exit();
}
if($email==''){
echo
"<script>window.open('Log.php?emailname=Email is Required','_self') </script>";
exit();
}
if($pass==''){
echo
"<script>window.open('Log.php?passname=Password is Required','_self') </script>";
exit();
}
if($rpass==''){
echo
"<script>window.open('Log.php?rpassname=Password is Required','_self') </script>";
exit();
}
$sql = "INSERT INTO student(Campus,User_id,Login,Email,password,Retype_password) values('$campus','$name','$u_id','$email','$pass','$rpass')";
if (mysqli_query($conn,$sql) {
echo "New record created successfully";
print '<script>alert("Successfully Registered!");</script>'; // Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to register.php
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
}
?>

Categories