I have some fairly large forms who's inputs need to be sequentially numbered. I need the use the sequential number twice for each field, for example...
<label>Label for 17</label>
<textarea name="q[17]"><?=$dataarray['q17']?></textarea>
<label>Label for 18</label>
<input type="text" name="q[18]" value="<?=$dataarray['q18']?>">
<label>Label for 19</label>
<textarea name="q[19]"><?=$dataarray['q19']?></textarea>
Is it possible to replace each number with a script call that will add the numbers for me? The main issue I'm having is if I need to update the forms with new fields, I need to re-number every following input manually.
I can't use a php loop as the input types vary, and I have other text and labels etc between the fields.
You say "I can't use a loop". I doubt that actually, as you could do something like:
<?php for($i = 0; $i < $max; $i++):
<?php if($fieldtype == 'text'): ?>
<input type="text" .... />
<?php elseif($fieldtype == 'select'): ?>
<select name="name">
... options
</select>
<?php else: ?>
etc....
<?php endif; ?>
<?php endfor; ?>
But anyway, if you insist, you could do this:
<?php $num = 1; ?>
<label>Label for <?php echo $num; ?></label>
<textarea name="q[<?php echo $num; ?>]"><?=$dataarray['q'. $num++]?></textarea>
<label>Label for <?php echo $num; ?></label>
<input type="text" name="q[<?php echo $num; ?>]" value="<?=$dataarray['q'. $num++]?>">
etc..
The trick is the $num++, use it the last time you want to print out the 'current number'. It is a post-incrementor, meaning it will be incremented by 1 after it's used.
Sure, you can use a for() loop inside PHP as follows:
function outputFields($num, $values)
{
$html = '';
for($i = 0; $i < $num; $i++)
{
$html.= '<textarea name="q['.($i + 1).']">'.$values['q'.($i + 1)].'</textarea>';
}
return $html;
}
Now, you just need to echo the returned value of this function, and pass in the number of fields to be generated, and also include the $datearray variable as a parameter.
For example, to output 20 fields, you can use:
<?php echo outputFields(20, $datearray) ?>
Try with:
for ($i = 0; $i < 20; $i++) {
echo '<textarea name="q[' . $i . ']">' . $dataarray['q' . $i] . '"></textarea>';
}
You could
$max = 19; //Or whatever
for( $i = 0; $i <= $max; $i++){ ?>
<textarea name="q[<?php echo $i; ?>]"><?=$dataarray['q' . $i]?></textarea><?php
}
But you might be better doing a foreach over $dataarray. Depends on your data structures.
Related
Hello guys I had an issue with datetimepicker on FF. In other browsers its doing good with the code I wrote. The problem is I have three drop down options. In each one I had, time is inserted by the user using datetimepicker but unfortunately the picker works only on one of the three of them. Any idea why this is happening
PHP CODE
<?php
echo '<div class="table-rsponsive overlap">';
echo '<table class="table" >';
$workingDaysNum = array();
$counter = 0;
for ($i = 0; $i < 3; $i++) {
echo '<tr>';
for ($j = 0; $j < 7/* count($spec) */; $j++) {
if ($i == 0) {
echo '<td>' . $days[$j] . '</td>';
} else {
$counter++;
$workingDaysNum[] = 'datetimepicker' . $counter;
?>
<td>
<div class="input-group date datetimepicker" id="<?php echo $workingDaysNum[$counter - 1] ?>">
<input class="form-control " id="filter-date" size="16" type="text" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</td>
<?php
}
}
echo '</tr>';
}
JQUERY CODE
$(function () {
<?php
foreach ($workingDaysNum as $workDay) {
echo '$(' . $workDay . ').datetimepicker({';
echo 'format: \'HH:mm\',';
echo 'stepping: 30';
echo '});';
}
?>
<?php
foreach ($workingDaysNum as $workDay) {
echo '$("' . $workDay . '").on("dp.change",function (e) {';
echo 'saveSpec1Modal("' . $workDay . '", $("' . $workDay . '").data(\'date\'))';
//echo 'console.log($("#'.$workDay.'").data(\'date\'))';
echo '});';
}
?>
});
Ditch the loops in the jQuery.
Instead of activating datetimepicker by ID, you have already given them all a class, so you can run it once instead of looping.
$(function () {
$('.datetimepicker').datetimepicker({
format: 'HH:mm',
stepping: 30
});
});
Same applies to the change function.
I am trying to get the value of the selected option from my select. And I am trying to see it's output through a javascript echo. Here's what I've got so far. I am not getting the value
<form method="post" action="">
<select class="form-control" name="empSel" id="empSel">
<?php
$sql2 = "SELECT * FROM employee";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row2 = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row2['lastname'] ?>"><?=
/*$row2['user_surname']." ".*/
$row2['id']."-".$row2['lastname'] ?></option>
<?php
}
?>
</select>
<Label> Confirm</Label>
<div class="form-group col-md-6">
<input type="submit" class="btn btn-block btn-info"
name="submit"/>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$userid = $_POST['empSel'];
echo '<script type="text/javascript"> alert('.$userid.')</script>';
$userid = preg_replace('/\D/', '', $userid);
$sql2 = "SELECT * FROM employee where id ='userid'";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row = mysql_fetch_assoc($result)) {
echo '<script type="text/javascript"> alert("")</script>';
}
}
?>
An javascript alert doesn't pop out on this code. However, when I switch the value in the echo to a different variable an alert pops up. What does it mean? Do I properly get the value of my select and the page refreshed instantly that I didn't get to see it? Thanks
Edit:
An example of the option value would be 1-Lastname
And here's what I've tried.
<?php
if (isset($_POST['empSel'])){
$userid = $_POST['empSel'];
$userid = intval($userid);
echo '<script type="text/javascript"> alert('.$userid.')</script>';
}
?>
Now the javascript alert shows, but it echo 0. I think I am still not getting the value of my selected option
<option value="<?php echo $row2['id'] ?>">
This fixed it. In my previous code the option value was the surname...
I have almost 200 images in my List.
$rings = $db->query("SELECT * FROM rings WHERE id > ". $ringId ." LIMIT 100");
I want to display them in a Gallery form with a Checkbox to each. Each Row must contains atleast 4 images with their checkboxes.
I have tried, making a for loop with adding div but that only adds vertically with on Ring at a time. How can i give it some sort of gallery look.
<div>
<?php
echo "<table><tr>";
$i =0;
foreach( $rings as $ring )
{
$i++;
echo '<td><input type="image" src="http://thevowapp.com/iphoneapp/vowstore/rings/'. $ring['imagePath'] .'" name="checked" value="' . $ring['id'].'" data-my-info="'. $ring['ringSetName'] .'" style="width:280px; height:280px;"></td>';
echo '<input type="checkbox">';
if( $i % 3 == 0 )
{
echo "</tr><tr>";
}
}
echo "</tr></table>";
?>
</div>
Your need to control the output so that it outputs horizontally until you have 4 images in that row, then start a new row.
Also, might I suggest a table structures for this.
echo "<table>
<tr>";
$i=0;
foreach( $rings as $ring ):
$i++
echo "<td><img src='{$ring['thumb']}' /></td>";
if( $i % 4 == 0 ){
echo "</tr><tr>";
}
}
echo "</tr></table>";
Consider incrementing a variable at each loop, for instance:
<?php
$loop = 0;
foreach ($items as $item) {
$loop++;
?>
<div class="col-md-3"><!-- My content --></div>
<?php
if ($loop == 4) {
$loop = 0;
?>
<div class="clearfix"></div>
<?php
}
}
i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>
I have a form which has some text fields. Text fields may increase or decrease according to database table. If there are 3 warehouses in database it will show 3 text boxes with available quantity as place holder. Now user have to enter quantity no more than given in placeholder in each box. How can I do validation if user enter a value more than available (which will be shown as place holder) ?. Problem is validation should be according to foreach loop. My code is below,
<?php
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php } }?>
Here as you see text boxes number is depending upon foreach loop. So how can I validate? Javascript or Ajax is ok.
I tried something like this,
<?php foreach ($ware_details as $data) {?>
<script>
function check()
{
var stock = document.getElementById('quantity').value;
var return_stock = document.getElementById('return_pro').value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro').focus();
return false;
}
//alert(return_stock);
return false;
}
But I know it is fully wrong. Any idea?
Try to use html5 required attribute. This set of code may help you.
<input type="number"
min="1"
max="<?php echo $data->wh_product_qty; ?>"
name="<?php echo $data->wh_warehouse_id;?>"
required="required"
placeholder="<?php echo $data->wh_product_qty; ?> Available" />
You cannot use an id multiple times in the document, it needs to be unique. Either use classes to identify/group elements, or enumerate the ids:
<?php
$i = 0;
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro<?php echo $i; ?>" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity<?php echo $i; ?>" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php
$i++;
} }?>
<script>
function check(i) {
var stock = document.getElementById('quantity'+i).value;
var return_stock = document.getElementById('return_pro'+i).value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro'+i).focus();
return false;
}
//alert(return_stock);
return false;
}
// then in the validation trigger:
for (var i=0; i< <?php echo $i; ?>; i++)
check(i);