I've got a form which currently works as a single line allowing different input fields based on the Production drop down.
i.e. If you choose CPE or CPM you get the inputs for Impressions and Targeting. If you choose Eggs2Go then you only get Impressions.
While this works so far, if I add a line and use the drop down menu it affects the first ID tag changing that line and not the new lines options.
function showTargetCheck(that) {
if (that.value == "CPM" || that.value == "CPE" || that.value == "SWIFT") {
document.getElementById("showTarget").style.display = "block";
document.getElementById("showImpressions").style.display = "none";
}
else if (that.value == "EGGS") {
document.getElementById("showImpressions").style.display = "block";
document.getElementById("showTarget").style.display = "none";
}
else {
document.getElementById("showTarget").style.display = "none";
document.getElementById("showImpressions").style.display = "none";
}
}
Is there a way I can give an auto increment to each new line so that the showTarget and ShowImpressions act individually?
Details in the fiddle
You can't repeat ID's in a page, they must be unique by definition.
The common approach to repeating rows like this is to use common classes for like elements and isolate instances within your event handlers by looking up to parent row element and then looking inside that specific row for needed elements
Assume we change all the repeating ID's to same class name you would then do something like the following in jQuery
$('#tableContainer').on('change', 'select', function(e){
// get row instance starting from `this`
var $row = $(this).closest('.tableRow'),
currVal = $(this).val(),
// flags for toggling various classes
showImpressions = false,
showTarget = false;
if (currVal == "CPM" || currVal == "CPE" || currVal == "SWIFT") {
showTarget = true;
}
// other conditionals to set flags based on other values
// now toggle display of instances of classes within row instance
$row.find('.showTarget').toggle(showTarget);
$row.find('.showImpressions').toggle(showImpressions);
});
As mentioned by charlietfl, ids are unique.
Using your existing coding format
Change all id to class
Find the second parentNodes of your select tag
Once the main parentNode is Found, find your siblings input boxes that you need to change
Snippet below
/*
New IO Line
*/
$('#addNewIOLine').click(function() {
$('#IOLine').append(
'<div class="tableRow">' +
'<div class="tableLeft">' +
'<input type="date" name="startDate" placeholder="MM/DD/YYYY" class="date">' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="date" name="endDate" placeholder="MM/DD/YYYY" class="date">' +
'</div>' +
'<div class="tableMiddle">' +
'<select name="products" onchange="showTargetCheck(this);">' +
'<option>Select one</option>' +
'<option disabled>---</option>' +
'<option value="PRODUCTION">Production</option>' +
'<option value="CPE">CPE</option>' +
'<option value="CPM">CPM</option>' +
'<option value="SWIFT">Swift</option>' +
'<option value="EGGS">Eggs2Go</option>' +
'</select>' +
'</div>' +
'<div class="showImpressions" style="display: none;">' +
'<div class="tableMiddle">' +
'<input type="number" placeholder="1000" class="imps">' +
'</div>' +
'</div>' +
'<div class="showTarget" style="display: none;">' +
'<div class="tableMiddle">' +
'<input type="text" placeholder="Targeting">' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="number" placeholder="1000" class="imps">' +
'</div>' +
'</div>' +
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="rates">' +
'</span>' +
'</div>' +
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="grosscost">' +
'</span>' +
'</div>' +
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="netcost">' +
'</span>' +
'</div>' +
'<div class="tableRight">' +
'<input type="text" placeholder="Notes" class="notes">' +
'</div>' +
'</div>');
});
#tableContainer {
display: table;
}
.tableRow {
display: table-row;
}
.tableLeft,
.tableRight,
.tableMiddle {
display: table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function showTargetCheck(that) {
if (that.value == "CPM" || that.value == "CPE" || that.value == "SWIFT") {
that.parentNode.parentNode.getElementsByClassName("showTarget")[0].style.display = "block";
that.parentNode.parentNode.getElementsByClassName("showImpressions")[0].style.display = "none";
} else if (that.value == "EGGS") {
that.parentNode.parentNode.getElementsByClassName("showImpressions")[0].style.display = "block";
that.parentNode.parentNode.getElementsByClassName("showTarget")[0].style.display = "none";
} else {
that.parentNode.parentNode.getElementsByClassName("showTarget")[0].style.display = "none";
that.parentNode.parentNode.getElementsByClassName("showImpressions")[0].style.display = "none";
}
}
</script>
<!-- IO Table -->
<div id="tableContainer">
<!-- IO Row -->
<div class="tableRow">
<!-- Start Date -->
<div class="tableLeft">
<h4>Start</h4>
<input type="date" name="startDate" placeholder="MM/DD/YYYY" class="date">
</div>
<div class="tableMiddle">
<h4>End</h4>
<input type="date" name="endDate" placeholder="MM/DD/YYYY" class="date">
</div>
<!-- End Date -->
<!-- Products -->
<div class="tableMiddle">
<h4>Products</h4>
<select name="products" onchange="showTargetCheck(this);">
<option>Select one</option>
<option disabled>---</option>
<option value="PRODUCTION">Production</option>
<option value="CPE">CPE</option>
<option value="CPM">CPM</option>
<option value="SWIFT">Swift</option>
<option value="EGGS">Eggs2Go</option>
</select>
</div>
<!-- Products -->
<!-- Show Impressions Only -->
<div class="showImpressions" style="display: none;">
<div class="tableMiddle">
<h4>Impressions</h4>
<input type="number" placeholder="1000" class="imps">
</div>
</div>
<!-- Show Impressions Only -->
<!-- Show Targeting & Impressions -->
<div class="showTarget" style="display: none;">
<div class="tableMiddle">
<h4>Targeting</h4>
<input type="text" placeholder="Targeting">
</div>
<div class="tableMiddle">
<h4>Impressions</h4>
<input type="number" placeholder="1000" class="imps">
</div>
</div>
<!-- Show Targeting & Impressions -->
<!-- Rates -->
<div class="tableMiddle">
<h4>Rate</h4>
<span class="input-symbol-dollar">
<input type="number" placeholder="0.00" min="0.01" class="rates">
</span>
</div>
<!-- Rates -->
<!-- Gross Cost -->
<div class="tableMiddle">
<h4>Gross</h4>
<span class="input-symbol-dollar">
<input type="number" placeholder="0.00" min="0.01" class="grosscost">
</span>
</div>
<!-- Gross Cost -->
<!-- Net Cost -->
<div class="tableMiddle">
<h4>Net</h4>
<span class="input-symbol-dollar">
<input type="number" placeholder="0.00" min="0.01" class="netcost">
</span>
</div>
<!-- Net Cost -->
<!-- Notes -->
<div class="tableRight">
<h4>Notes</h4>
<input type="text" placeholder="Notes" class="notes">
</div>
<!-- Notes -->
</div>
<!-- IO Row -->
</div>
<!-- ADD NEW IO LINE -->
<div id="IOLine"></div>
<button type="button" id="addNewIOLine">+ Add New Line</button>
<!-- ADD NEW IO LINE -->
(Posted on behalf of the OP).
Working version here if anyone needs the reference:
/*
Toggle Impressions and Targeting Fields
*/
$('#tableContainer').on('change', 'select', function(e) {
// get row instance starting from `this`
var $row = $(this).closest('.tableRow'),
currVal = $(this).val(),
showImpressions = true,
showTarget = true,
showDefault = true;
if (currVal == "CPM" || currVal == "CPE" || currVal == "SWIFT") {
showTarget = true;
showImpressions = false;
showDefault = false;
} else if (currVal == "EGGS") {
showImpressions = true;
showTarget = false;
showDefault = false;
} else if (currVal == "DEFAULT" || currVal == "") {
showDefault = true;
showTarget = false;
showImpressions = false;
}
// other conditionals to set flags
// now toggle instances of classes within row
$row.find('.showTarget').toggle(showTarget);
$row.find('.showImpressions').toggle(showImpressions);
$row.find('.showDefault').toggle(showDefault);
});
/*
New IO Line
*/
$('#addNewIOLine').click(function() {
$('#IOLine').append(
'<div class="tableRow">' +
/* DATES */
'<div class="tableLeft">' +
'<input type="date" name="startDate" placeholder="MM/DD/YYYY" class="date">' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="date" name="endDate" placeholder="MM/DD/YYYY" class="date">' +
'</div>' +
/* PRODUCTS */
'<div class="tableMiddle">' +
'<select name="products">' +
'<option value="DEFAULT">Production</option>' +
'<option value="CPE">CPE</option>' +
'<option value="CPM">CPM</option>' +
'<option value="SWIFT">Swift</option>' +
'<option value="EGGS">Eggs2Go</option>' +
'</select>' +
'</div>' +
/* Show Default */
'<div class="showDefault">' +
'<div class="tableMiddle">' +
'<input type="text" placeholder="N/A" disabled>' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="number" placeholder="N/A" class="imps" disabled>' +
'</div>' +
'</div>' +
/* Show Impressions Only */
'<div class="showImpressions">' +
'<div class="tableMiddle">' +
'<input type="text" placeholder="N/A" disabled>' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="number" placeholder="1000" class="imps">' +
'</div>' +
'</div>' +
/* Show Targeting & Impressions */
'<div class="showTarget">' +
'<div class="tableMiddle">' +
'<input type="text" placeholder="Targeting">' +
'</div>' +
'<div class="tableMiddle">' +
'<input type="number" placeholder="1000" class="imps">' +
'</div>' +
'</div>' +
/* RATES */
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="rates">' +
'</span>' +
'</div>' +
/* GROSS COST */
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="grosscost">' +
'</span>' +
'</div>' +
/* NET COST */
'<div class="tableMiddle">' +
'<span class="input-symbol-dollar">' +
'<input type="number" placeholder="0.00" min="0.01" class="netcost">' +
'</span>' +
'</div>' +
/* NOTES */
'<div class="tableRight">' +
'<input type="text" placeholder="Notes" class="notes">' +
'</div>' +
'</div>');
});
http://jsfiddle.net/16godohe/9/.
Related
I have use this form for uploading multiple files. But i have used jQuery for append multiple file input. I have try multiple method for validate in laravel but its not working. If we used only single file validate its working. But if we used multi file validation its not working.
If we use this and upload all file at a time in with multiple attribute file input its working.
If we upload multiple file one by one after that its not working.
// My View
#include('flash.flash_message')
<form action="{{route('company.upload')}}" method="post" id="formUpload">
<div id="newinput">
<input type="file" name="files[]" class="form-control" />
</div>
<input type="submit" value="uplaod" />
</form>
<div class="btn btn-info" id="add_btn">Add</div>
// My jQuery
$(document).on('click','#add_btn',function(){
var newRowAdd =
'<input type="file" name="files[]" class="form-control" />';
$('#newinput').append(newRowAdd);
});
// My Controller
<?php
public function store(Request $request)
{
$request->validate([
'files' => 'required',
'files.*' => 'mimes:doc,docx|max:15720',
] );
try
{
$array = [
'created_at'=>date('Y-m-d H:i:s')
];
$data = Company::create($array);
// there my uplaoding code
if($request->hasFile('file'))
{
$newData = Company::findOrFail($data->id);
$docs = array();
$files = $request->file('file');
if($files){
foreach($files as $file) {
$fileName = time().rand(100000,999999).'_'.$data->id.'.'.$file->extension();
$docs[] = $fileName;
$file->move(public_path('company'), $fileName);
}
}
$newData->doc = !empty($result) ? serialize($result) :'';
$newData->updated_at = date('Y-m-d H:i:s');
$newData->save();
}
}
catch(\Exception $e)
{
return redirect()->back()->with('error',$e->getMessage());
}
}
// I Also used this
$input_data = $request->all();
$validator = Validator::make(
$input_data, [
'files.*' => 'required|mimes:jpg,jpeg,png,bmp|max:20000'
],[
'files.*.required' => 'Please upload an image',
'files.*.mimes' => 'Only jpeg,png and bmp images are allowed',
'files.*.max' => 'Sorry! Maximum allowed size for an image is 20MB',
]
);
if ($validator->fails()) {
// Validation error..
}
var i = 1;
jQuery("#addRow").click(function () {
var html = '';
var scr = '';
html += '<div id="addedRow" class="form-row mb-4">';
html += '<div class="form-group col-md-4">';
html += '<label for="filename[' + i + ']">File type</label>';
html += '<span class="text-danger">*</span>';
html += '<select class="form-control" id="filename' + i + '" name="filename[' + i + ']" required><option selected="selected" value="">Select file type</option><option value="claim">Claim</option><option value="reimbursements">Reimbursements</option><option value="policy">Policy</option><option value="ecards">Ecards</option><option value="data">Data</option><option value="others">Others</option></select>';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Select the file type you are uploading/linking</small>';
html += '</span>';
html += '</div>';
html += '<div id="Other' + i + '" class="form-group col-md-4">';
html += '<label for="other[' + i + ']">Specify file type</label> <span class="text-danger">*</span>';
html += '<input class="form-control" placeholder="Specify the file type" name="other[' + i + ']" type="text" id="other[' + i + ']" >';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Specify the file type as you selected the file as "Other"</small>';
html += '</span>';
html += '</div>';
html += '<div id="upload' + i + '" class="form-group col-md-4">';
html += '<label for="upload[' + i + ']">Upload file</label>';
html += '<span class="text-danger">*</span>';
html += '<input class="form-control" name="upload[' + i + ']" type="file" id="upload[' + i + ']" required>';
html += '<span class="badge">';
html += '<small id="sh-text4" class="form-text mt-0">Upload the file | Formats allowed: <strong>PDF, DOC, ZIP, JPG, PNG GIF and Excel</strong></small></span>';
html += '</div>';
html += '<div class="form-group col-md-4" style="padding-top: 30px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
html += '</div>';
html += '</div>';
jQuery('#newRow').append(html);
scr += '<script';
scr += '>$(document).ready(function(){ $("#filename' + i + '").change(function () { if ($(this).val() === "others") {$("#Other' + i + '").show(); document.getElementById("other[' + i + ']").required=true}else{ $("#Other' + i + '").hide(); document.getElementById("other[' + i + ']").required=false;}}); $("#Other' + i + '").hide(); }); </';
scr += 'script>';
jQuery('#newScript').append(scr);
i++;
});
// remove row
jQuery(document).on('click', '#removeRow', function () {
i--;
$(this).closest('#addedRow').remove();
});
This is how I have implemented this in my project you can see there is a variable that you need to pass here
<input type="file" name="files['+i+']" class="form-control" />;
You have to increase the value of i once the row is added
There is no problem when the form is sent normally, but when I click on the add-phone button with jquery, input
I have an inpute with name sub_phone_ and when I post it, it is saved in the content named sub_email, sub_map and sub_maps which I did not add to the database in php. I want that if there are no email map maps inputs, they should not write them in the database.
database record
[{"title":"1","address":"1","phone":"1","submenu":[{"email":"1","phone":null,"map":null,"maps":null}]}]
if empty
"phone":null,"map":null,"maps":null <<< delete.
HTML
<form action="" method="post" class="formify">
<div class="tab-pane" id="iletisim">
<div id="menus">
<ul id="menu" class="menu">
<li>
<div class="menu-item">
<a href="#" class="delete-menu">
<i class="fa fa-times"></i>
</a>
<div class="row">
<label class="col-sm-2 col-form-label">title</label>
<div class="col-sm-7">
<div class="form-group bmd-form-group">
<input class="form-control" type="text" name="title[]" placeholder="title">
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 col-form-label">address</label>
<div class="col-sm-7">
<div class="form-group bmd-form-group">
<textarea class="form-control" name="address[]" cols="30" rows="3" placeholder="address""></textarea>
</div>
</div>
</div>
<div class="row">
<label class="col-sm-2 col-form-label">Phone</label>
<div class="col-sm-7">
<div class="form-group bmd-form-group">
<input class="form-control" type="text" name="phone[]" placeholder="Phone">
</div>
</div>
</div>
</div>
<div class="sub-menu">
<ul class="menu"></ul>
</div>
Add Email
Add Phone
Add Map
</li>
</ul>
</div>
</div>
<div class="menu-btn">
<button type="submit" value="1" name="submit" >Save</button>
</div>
</form>
JQUERY
$(document.body).on('click', '.add-email', function (e) {
var index = $(this).closest('li').index();
$(this).prevAll('.sub-menu:last').find('ul').append('<li>\n' +
'<div class="handle"></div><div class="menu-item">\n' +
' <a href="#" class="delete-menu">\n' +
' <i class="fa fa-times"></i>\n' +
' </a>\n' +
' <div class="row">\n' +
' <label class="col-sm-2 col-form-label">İletişim Maili</label>\n' +
' <div class="col-sm-7">\n' +
' <div class="form-group bmd-form-group">\n' +
' <input class="form-control" type="text" name="sub_email_' + index + '[]" '
+ 'placeholder="İletişim Maili">\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</li>');
e.preventDefault();
});
$(document.body).on('click', '.add-phone', function (e) {
var index = $(this).closest('li').index();
$(this).prevAll('.sub-menu:last').find('ul').append('<li>\n' +
'<div class="handle"></div><div class="menu-item">\n' +
'<a href="#" class="delete-menu">\n' +
' <i class="fa fa-times"></i>\n' +
'</a>\n' +
' <div class="row">\n' +
' <label class="col-sm-2 col-form-label">İletişim 2. Telefon</label>\n' +
' <div class="col-sm-7">\n' +
' <div class="form-group bmd-form-group">\n' +
' <input class="form-control" type="text" name="sub_phone_' + index + '[]" '
+ 'placeholder="İletişim 2. Telefon">\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</li>');
e.preventDefault();
});
$(document.body).on('click', '.add-map', function (e) {
var index = $(this).closest('li').index();
$(this).prevAll('.sub-menu:last').find('ul').append('<li>\n' +
'<div class="handle"></div><div class="menu-item">\n' +
' <a href="#" class="delete-menu">\n' +
' <i class="fa fa-times"></i>\n' +
' </a>\n' +
' <div class="row">\n' +
' <label class="col-sm-2 col-form-label">Yol Tarifi URL Adresi</label>\n' +
' <div class="col-sm-7">\n' +
' <div class="form-group bmd-form-group">\n' +
' <input class="form-control" type="text" name="sub_map_' + index + '[]" '
+ 'placeholder="Yol Tarifi URL Adresi">\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</li>');
e.preventDefault();
});
$(document.body).on('click', '.add-maps', function (e) {
var index = $(this).closest('li').index();
$(this).prevAll('.sub-menu:last').find('ul').append('<li>\n' +
'<div class="handle"></div><div class="menu-item">\n' +
' <a href="#" class="delete-menu">\n' +
' <i class="fa fa-times"></i>\n' +
' </a>\n' +
' <div class="row">\n' +
' <label class="col-sm-2 col-form-label">Map Görseli URL Adresi</label>\n' +
' <div class="col-sm-7">\n' +
' <div class="form-group bmd-form-group">\n' +
' <input class="form-control" type="text" name="sub_maps_' + index + '[]" '
+ 'placeholder="Map Görseli URL Adresi">\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
'</div>\n' +
'</li>');
e.preventDefault();
});
PHP
if (post('submit')) {
$menu = [];
$menu_title = post('menu_title');
if (!$menu_title) {
$error = 'Menü Başlığını Belirtin!';
} elseif (count(array_filter(post('title'))) == 0) {
$error = 'En Az Bir Menü İçeriği Girmeniz Gerekiyor!';
} else {
$address = post('address');
$phone = post('phone');
foreach (post('title') as $key => $title) {
$arr = [
'title' => $title,
'address' => $address[$key],
'phone' => $phone[$key],
];
if (post('sub_email_' . $key)) {
$submenu = [];
$subphone = post('sub_phone_' . $key);
$submap = post('sub_map_'.$key);
$submaps = post('sub_maps_'.$key);
foreach (post('sub_email_' . $key) as $k => $subemail) {
$submenu[] = [
'email' => $subemail,
'phone' => $subphone[$k],
'map' => $submap[$k],
'maps' => $submaps[$k]
];
}
$arr['submenu'] = $submenu;
}
$menu[] = $arr;
}
$query = $db->prepare('INSERT INTO menu SET menu_title = :menu_title, menu_content = :menu_content');
$result = $query->execute([
'menu_title' => $menu_title,
'menu_content' => json_encode($menu)
]);
You can Try following code.
foreach (post('title') as $key => $title) {
$arr = [
'title' => $title,
'address' => $address[$key],
'phone' => $phone[$key],
];
if (post('sub_email_' . $key) != null) {
if (post('sub_email_' . $key)) {
$submenu = [];
$subphone = post('sub_phone_' . $key);
$submap = post('sub_map_' . $key);
$submaps = post('sub_maps_' . $key);
foreach (post('sub_email_' . $key) as $k => $subemail) {
if (($subphone[$k] != null) && ($submap[$k] != null) && ($submaps[$k] != null)) {
$submenu[] = [
'email' => $subemail,
'phone' => $subphone[$k],
'map' => $submap[$k],
'maps' => $submaps[$k]
];
}
}
if (count($submenu) > 0) {
$arr['submenu'] = $submenu;
}
}
}
$menu[] = $arr;
}
$result=DB::table('menu')
->insert([
'menu_title' =>$menu_title,//your menu title here
'menu_content' => json_encode($menu)
]);
I hope it's works for you.
I am trying to submit two dropdown lists with JSON data into my database table. I can get as far as the data inserted into the table but the 'date' and 'time' columns show the ID and parent ID instead of the date and times that are available in the dropdowns. Can anyone tell me why this is? (Main relevant code showing)
<?php
session_start();
include('includes/config.php');
error_reporting(0);
if (isset($_POST['submit'])) {
$arenadate = $_POST['date'];
$arenatime = $_POST['time'];
$useremail = $_SESSION['login'];
$sql = "INSERT INTO tblbooking(userEmail,ArenaDate,ArenaTime) VALUES(:useremail,:date, :time)";
$query = $dbh->prepare($sql);
$query->bindParam(':useremail', $useremail, PDO::PARAM_STR);
$query->bindParam(':date', $arenadate, PDO::PARAM_STR);
$query->bindParam(':time', $arenatime, PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
echo "<script>alert('Booking successful.');</script>";
}
else {
echo "<script>alert('Something went wrong. Please try again');</script>";
}
}
?>
<form action="" method="post">
<div class="contact_form gray-bg">
<div class="form-group">
<label for="" class="control-label">Select Date</label>
<select name="date" id="date" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Date</option>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Select Time</label>
<select name="time" id="time" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Time</option>
</select>
</div>
<?php if ($_SESSION['login']) {
?>
<div class="modal-footer text-center">
<input type="submit" name="submit" value="Confirm Booking"
class="btn btn-xs uppercase">
</div>
<?php } else { ?>
<a href="#loginform" class="btn btn-xs uppercase" data-toggle="modal"
data-dismiss="modal">Login To Book Seat</a>
<?php } ?>
</div>
</div>
</div>
</form>
</div>
</div>
</section>
<script>
$(document).ready(function (e) {
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
get_json_data('date', 0);
$(document).on('change', '#date', function () {
var date_id = $(this).val();
if (date_id != '') {
get_json_data('time', date_id);
} else {
$('#time').html('<option value="">Select Time</option>');
}
});
});
</script>
You are overwriting the empty option in #date so that isn't really needed in the html. You can change the following line from:
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
to:
html_code += '<option value="' + value.avail + '" data-id="'+value.id+'">' + value.avail + '</option>';
The posted value for 'date' and 'time' will be the selected options value attribute, but this will break selecting the date and getting the time based on that id. In this case you could add a data-id attribute and use that to get the time which means the following code would change from:
var date_id = $(this).val();
to:
var date_id = $(this).data('id');
Don't set the value attribute of an <option> tag unless you want the form to receive that value instead of the visible text.
If you write an option like this inside of a <select name="date">:
<option value="">Select an option</option>
Then the POSTing form will deliver $_POST['date'] = ''.
If you write:
<option>Select an option</option>
Then the POSTing form will deliver $_POST['date'] = 'Select an option'.
In terms of form delivery, there is never a need to duplicate the option text as a value.
If you want to store data inside of each <option> tag, I'll give the same advice as aCMoFoCord because data- attributes are clean and flexible regarding the values that they can hold.
Specifically, I'm saying:
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option data-id="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
Then:
$(document).on('change', '#date', function () {
if ($(this).val() != '') {
get_json_data('time', $(this).data('id'));
} else {
$('#time').html('<option value="">Select Time</option>');
}
});
So I have this form:
<form data-ajax="false" name="frm" action="cmd_go.php" method="post" >
<input type="hidden" name="cmd" value="insertarlineapedidomultiple">
<input type="hidden" name="mod" value="yes">
<!--<input id="insertList" type="hidden" name="insertList" value="">-->
<input type="hidden" name="o" value="<?php echo $o ?>">
<div id="div_lista_familias" data-role="collapsibleset" data-content-theme="a" data-iconpos="right">
</div>
<input class="insertar btn-azul ui-btn ui-corner-all" data-role="none" type="submit" value="Insertar"/>
</form>
Then we have some Javascript code to populate the form content after calling a web service:
function listaProductos(alb, fam){
var ok = false;
$.ajax({
type: 'GET',
url: url_servicio + alb + '/' + fam + '/productos',
dataType: "json", // data type of response
//async: false,
error: function(){
ok = false;
},
success: function(data){
var content;
var acum = 0;
for(i=0; i<data.length; i++){
ok = true;
var qty = get_item_qty_inline(data[i].itemid);
var qty2 = get_item_qty2_inline(data[i].itemid);
var qty3 = get_item_qty3_inline(data[i].itemid);
var dto = get_item_dto1_inline(data[i].itemid);
content = '<fieldset class="ui-grid-d">';
content += '<div class="ui-block-a"><label for="name">';
content += data[i].itemid + ' ' + data[i].nombre + '</div>';
content += '<div class="ui-block-c ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty + '" placeholder="Uds1" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-b ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number" name="dtoporc1[]" pattern="[0-9]*" id="number-pattern"'
content += ' value="' + dto + '" placeholder="%Dto1"></div>';
content += '<div class="ui-block-d ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad2[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty2 + '" placeholder="Uds2" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<div class="ui-block-e ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset""><input type="number"';
content += ' name="cantidad3[]" pattern="[0-9]*" id="number-pattern"';
content += ' value="' + qty3 + '" placeholder="Uds3" onfocus="this.oldvalue = this.value;" onchange="onChangeQty(this); this.oldvalue = this.value;"></div>';
content += '<input type="hidden" name="idalbaran[]" value="' + alb +'">';
content += '<input type="hidden" name="itemid[]" value="' + data[i].itemid +'">';
content += '<input type="hidden" name="famalbaran[]" value="' + fam +'">';
content += '<input type="hidden" name="itemdesc[]" value="' + data[i].nombre +'">';
content += '<input type="hidden" name="precioventa[]" value="' + data[i].precio + '">';
content += '<input type="hidden" name="dtoporc2[]" value>';
content += '<input type="hidden" name="dtoporc3[]" value>';
$('#'+fam.replace(/ /g, '_')+'_content').append(content);
acum += parseFloat(qty || 0) + parseFloat(qty2 || 0) + parseFloat(qty3 || 0);
$('#'+fam.replace(/ /g, '_')+' .ui-li-count').html(acum);
}
},
complete: function(data, status){
if (!ok){
$('#'+fam.replace(/ /g, '_')).remove();
}
}
});
}
Finally, this is the PHP code we have in cmd_go.php
//GET variables
if(isset($_GET)){
$params = array_keys($_GET);
for ($i=0;$i<count($params);$i++)
if(isset($_GET[$params[$i]])){
$nv=$params[$i];
$$nv=$_GET[$params[$i]];
}
}
//POST variables
if(isset($_POST)){
$params = array_keys($_POST);
for($i=0;$i<count($params);$i++)
if(isset($_POST[$params[$i]])){
$nv=$params[$i];
$$nv=$_POST[$params[$i]];
//print "$nv : ".$$nv.'<br />';
}
}
var_dump($itemid);
The problem is that not all values are posted, because our $itemid array only has 91 elements, when our web service returns about 400. Out HTML form is correctly displayed with all 400 items, but out PHP var_dump returns:
array(91){[0]=>string(6) "173771" [1]=>string(6) "173772" [2]=>string(6) "564814"...[90]=>string(6) "548115"}
Any ideas on why POST could be taking only 91 records??
You need to check max_input_vars value in php.ini. It can lead to such behavior.
http://php.net/manual/en/info.configuration.php#ini.max-input-vars
In form, I will be adding product info in. looping name eg. pname1, pname2 when add.
I realise now that when i wanna send to email we need the 'name'. what code should i put on php file to loop the pname?
noted: my form and php code is not in the same file.
or i should put them together and click to loop?
Php file put this?
<?php
$x=1;
while($x<=10)
{
echo "The number is: $x <br>";
echo ;
$x++;
}
?>
form in html
<div class="" id="" name="productlist"> <!-- Add Product Here -->
<ol><input class="fpname" type="text" id="addpname"placeholder="Product Name"/><input class="fpqty" type="number" id="addpqty" placeholder="Quantity"/><input class="fpprice" type="text" id="addpprice" placeholder="Price per Item"/><input type="button" id="padd" value="add"/>
</br><font color="red" size="1.5"><i>*Becareful when adding the Product, once added you are unable to edit the information except changing the quantity.</i></font>
</ol>
<ol id="addhereform"><input type="text" class="fpname" value="Product Name" readonly/><input class="fpqty" type="text" id="pqty" value="Quantity" readonly/><input type="text" class="fpprice" value="Total Price" readonly/>
</ol>
<ol><input class="fpname" id="fpships" type="text" Value="" readonly/><input class="fpqty" id="overallqty" type="text" value="" readonly/><input class="fpprice" type="text" id="overallprice" value="" readonly/>
</ol> <!-- Result -->
</div> <!-- Add Product End Here -->
jquery add button
var count = 1;
$('#padd').click(function(){
var pname = $('#addpname').val();
var pqty = $('#addpqty').val();
var pprice = $('#addpprice').val();
var totalpprice = (pqty * pprice).toFixed(2);
$('#addhereform').append('<li><input class="fpname" type="text" id="pname" name="pname' + count + '" value="' + pname + '" readonly/><input class="fpqty" type="number" id="pqty" name="pqty' + count + '" value="' + pqty + '"/><input type="text" id="pprice" name="pprice' + count + '" value="' + pprice + '" readonly hidden/><input class="fpprice" type="text" id="totalpprice" name="totalpprice' + count + '" value="' + totalpprice + '" readonly/><input type="button" id="premove" value="X"/></li>').before('</li>');
count++;
});
Ans:
$name1 = $_POST["name1"];
$name2 = $_POST["name2"];
$name3 = $_POST["name3"];
# and so on...
for($i = 1; $i <=5; $i++){
$productlist = ${'name' . $i};
echo $productlist;}
Thanks for everyones help,
Here's another method(better) I just found. no need to type all the super long loop way.
Stristr is find name keyword.
if($_POST){
foreach($_POST as $key => $value){
if(stristr($k, 'pname')){
echo "$v";
}
if(stristr($k, 'pqty')){
echo "$v";
}
if(stristr($k, 'pprice')){
echo "$v";
}
if(stristr($k, 'ptotalprice')){
echo "$v</br>";
}
}
}