get value from dropdown. (little tricky) - php

First of all, im quite new to PHP and coding, but here goes.
I have a web form, that has to get some info from a txt file (located in a folder on the server)
I got how to make it get the info from the file and how to make the dropdown list, show all files in the folder.
How ever what i cant figure out is how to make them work together, so the file name it reads from, is taken from the selected value of the dropdown list.
the code for the dropdown list:
<?
$currentdir = 'files'; //change to your directory
$dir = opendir($currentdir);
echo 'Files are as follows:<br>';
echo '<select name="select">';
while($file = readdir($dir))
{
echo '<option value="'.$file.'">'.$file.'</option>';
}
echo '</select>';
closedir($dir); ?>
and the code to read from the file:
<input type="text" value="<?php $myFile = ""; $lines = file($myFile); echo $lines[2]; ?>" name="refnr" id="refnr" class="input" />
lets say the drop down shows 2 files, test.txt and test2.txt, if i select test2.txt from the dropdown, i wanted it to put "test2.txt" in between the "" at <?php $myFile = "";
but no matter how i try to put the code in there to get the selected value, it just fails...
The full code of my Form as it is right now:
<?php
if (!empty($_POST)) {
// Used for later to determine result
$success = $error = false;
// Object syntax looks better and is easier to use than arrays to me
$post = new stdClass;
// Usually there would be much more validation and filtering, but this
// will work for now.
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
// Check for blank fields
if (empty($post->refnr))
$error = true;
else {
// Get this directory, to include other files from
$dir = dirname(__FILE__);
// Get the contents of the pdf into a variable for later
ob_start();
require_once($dir.'/pdf.php');
$pdf_html = ob_get_contents();
ob_end_clean();
// Load the dompdf files
require_once($dir.'/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF(); // Create new instance of dompdf
$dompdf->load_html($pdf_html); // Load the html
$dompdf->render(); // Parse the html, convert to PDF
$pdf_content = $dompdf->output(); // Put contents of pdf into variable for later
// Get the contents of the HTML email into a variable for later
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// Load the SwiftMailer files
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer
$message = Swift_Message::newInstance()
->setSubject('Felanmalan') // Message subject
->setTo(array('mymail#hidden' => 'Fel')) // Array of people to send to
->setFrom(array('mymail#hidden' => 'Fel')) // From:
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::newInstance($pdf_content, 'Felanmalan.pdf', 'application/pdf')); // Attach the generated PDF from earlier
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Felanmälan från IKEA</title>
<style type="text/css">
html, body, h1, h2, h3, h4, h5, h6, p, span, ul, li, div, form, input, select, textarea, button {margin:0; padding:0;}
ul {list-style:none;}
a, a:hover {text-decoration:none; outline:0;}
a img {border:0;}
body {font:12px/16px Verdana, Arial, sans-serif; background:#ffffff;}
#container {width:450px; margin:10px auto; padding:10px; overflow:hidden; border:1px solid #000; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px; background:#F9F9F9;}
#container h1 {margin-bottom:20px; font-size:40px; line-height:40px; font-family:'HelveticaNeue-Light', 'Helvetica Neue', Helvetica, Arial, sans-serif; font-weight:normal;}
.message {margin-bottom:10px; padding:5px;}
.success {color:#4F8A10; border:1px solid #4F8A10; background:#DFF2BF;}
.error {color:#D8000C; border:1px solid #D8000C; background:#FFBABA;}
label {display:block; margin-bottom:3px; cursor:pointer;}
.input, textarea, select, button {display:block; width:440px; margin-bottom:10px; padding:3px; font:22px/22px 'HelveticaNeue-Light', 'Helvetica Neue', Helvetica, Arial, sans-serif; border:1px solid #CCC; border-top-width:2px;}
textarea {font-size:13px; line-height:16px;}
select {width:396px;}
button {float:right; width:auto; margin-bottom:0; padding:3px 30px; cursor:pointer; font-size:16px; border:1px solid #999; border-bottom-width:2px; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; background:#EEE;}
button:active {border-bottom-width:1px; padding:4px 30px 3px; background:#E9E9E9;}
</style>
</head>
<body>
<?
$currentdir = 'files'; //change to your directory
$dir = opendir($currentdir);
echo 'Files are as follows:<br>';
echo '<select name="select">';
while($file = readdir($dir))
{
echo '<option value="'.$file.'">'.$file.'</option>';
}
echo '</select>';
closedir($dir); ?>
<div id="container">
<h1><img src="felimg.png" /> Felanmälan</h1>
<?php if ($success) { ?>
<div class="message success">
<h4>Congratulations! It worked! Now check your email.</h4>
</div>
<?php } elseif ($error) { ?>
<div class="message error">
<h4>Sorry, an error occurred. Try again!</h4>
</div>
<?php } ?>
<form method="post" action="">
<label for="date"><b>Date:</b></label>
<input type="text" readonly name="date" id="date" class="input" value="<? print(Date("Y-m-d")); ?>"/>
<label for="refnr"><b>Referensnummer:</b></label>
<input type="text" value="<?php $myFile = ""; $lines = file($myFile); echo $lines[2]; ?>" name="refnr" id="refnr" class="input" />
<label for="bestav"><b>Beställd av:</b></label>
<input type="text" name="bestav" id="bestav" class="input" />
<label for="tel"><b>Tel:</b></label>
<input type="text" name="tel" id="tel" class="input" />
<label for="email"><b>Email:</b></label>
<input type="text" name="email" id="email" class="input" />
<label for="kund"><b>Kund:</b></label>
<textarea name="kund" id="kund" rows="4" cols="40"></textarea>
<label for="ktel"><b>Tel:</b></label>
<input type="text" name="ktel" id="ktel" class="input" />
<label for="art"><b>Berörd Artikel:</b></label>
<textarea name="art" id="art" rows="3" cols="40"></textarea>
<label for="fel"><b>Fel på varan: </b></label>
<textarea name="fel" id="fel" rows="2" cols="40"></textarea>
<label for="q1"><b>Installation gjord av fackman:</b></label>
<select name="q1" id="q1">
<option value="Ja">Ja</option>
<option value="Nej">Nej</option>
</select>
<label for="q2"><b>Serviceverkstad:</b></label>
<input type="text" name="q2" id="q2" class="input" />
<label for="q3"><b>Servicenr:</b></label>
<input type="text" name="q3" id="q3" class="input" />
<label for="q4"><b>Serienr:</b></label>
<input type="text" name="q4" id="q4" class="input" />
<label for="q5"><b>Inom garanti eller reklamation:</b></label>
<select name="q5" id="q5">
<option value="Garanti">Garanti</option>
<option value="Reklamation">Reklamation</option>
</select>
<label for="q6"><b>Informerat om punkt 8:</b></label>
<select name="q6" id="q6">
<option value="Ja">Ja</option>
<option value="Nej">Nej</option>
</select>
<label for="q7"><b>Har kund själv gått igenom manual för felsökning:</b></label>
<select name="q7" id="q7">
<option value="Ja">Ja</option>
<option value="Nej">Nej</option>
</select>
<label for="q8"><b>Ordernr:</b></label>
<input type="text" name="q8" id="q8" class="input" />
<label for="q9"><b>Inköpsdatum:</b></label>
<input type="date" name="q9" id="q9" class="input" /><br>
<p><button type="submit">Submit!</button></p>
</form>
</div>
</body>
</html>
hope it makes sense and again, sorry if it turns out to be a noob question :) i have used 2 days googling and testing and i have simply come to a point where i need a little push in the right direction again.
Thanks in advance.
p.s to explain short what my goal is, then i have 1 webform that generates a txt file and saves it on a server, then another form, where the "admin" can choose the file from the drop down, get the info in that the client filled out in the txt version and then fill out what he needs to fill out and then have it saved and sent as a PDF to a technician.

You could use
echo '<select id="select" name="select">';
while($file = readdir($dir))
{
echo '<option value="'.$file.'">'.$file.'</option>';
}
echo '</select>';
And after it has been loaded to the DOM, use
document.getElementById('select').onchange=changeSelect;
function changeSelect(){
document.getElementById('refnr').value=document.getElementById('select').value;
}
changeSelect();
See it here: http://jsfiddle.net/7nzBS/

I wanted it to put "test2.txt" in between the "" at `<?php $myFile = ""`
You can't do such a thing, because the "text2.txt" is at the client side and the $myfile, php variable, is at the server side. If you want to access data of a client side from server side, you need to send data via HTTP. So you have two choices:
Send the selected value via HTTP post or get.
Send the selected value via AJAX.

Thank you Oriol, that worked :)
the code now looks like this and is working as i needed it to.
Also thanks for all other suggestions, lovely with quick and helpful replies :)
<label for="refnr"><b>Referensnummer:</b></label>
<input type="text" value="<?php $selectedfile = #$_POST['file2']; $myFile = "files/$selectedfile"; $lines = file($myFile); echo $lines[0]; ?>" name="refnr" id="refnr" class="input" />

Related

PHP CSS how to add some style to existing style

I have this scenario in a PHP file:
<input type="text" id="myinput" minlength="6" maxlength="6" value="..." onkeyup="..." onfocusout="..." style="width: 20%; display: inline;" />
where I'd like to add some css if I got an error... I tried first with :
<input type="text" id="myinput" minlength="6" maxlength="6" value="..." onkeyup="..." onfocusout="..." style="width: 20%; display: inline;" <?php if($this->error == "2"){ echo 'style="border:2px solid red;"'; } ?> />
but it didn't applied because there is already a CSS... then I tried calling
?><script>$("#myinput").addClass('k3_border_ko');</script><?php
in the place of code where I encounter an error on that input but it didn't applied...
How I can apply adding that border color red if I have already a style in this way?
Thanks in advance!
Cheers! :-)
a simple approach would be
$style_noerr = '...';
$style_err = '...';
<input ... <?php if($this->error == "2"){ echo $style_err; } else {echo $style_noerr ;} ?> />
irrelevant note: your input has no name field but you'll need.

My PHP credit card form not recognizing certain inputs and errors

I was following a tutorial from John Conde on Authorize.net's credit card input form using PHP and error dectection.
It went perfect but I decided to add input boxes for entering the payment amount and and removed the unneeded shipping address requirements;
Now when the submitted form inputs are incorrect or empty, they no longer turn red nor does the "amount" box actually recognize whether it's empty or filled. The error box still pops up to bad credit card submissions.
Here's the page(minus the design to simplify trouble shooting);
http://teetimelawncare.com/payment-form.php
EDIT: removed the non-credit card related code and stuff like the state and year expiration dates to make it smaller. the PHP code at the very bottom is for the red error popup box that shows to the user when they incorrectly fill out the form.
I was at this part of the tutorial if anyone wants to compare:
http://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/Handling-Online-Payments-Part-5-Processing-Payment-and-Handling/ba-p/10768
Code:
<?php
$errors = array();
if ('POST' === $_SERVER['REQUEST_METHOD'])
{
$credit_card = sanitize($_POST['credit_card']);
$expiration_month = (int) sanitize($_POST['expiration_month']);
$expiration_year = (int) sanitize($_POST['expiration_year']);
$cvv = sanitize($_POST['cvv']);
$cardholder_first_name = sanitize($_POST['cardholder_first_name']);
$cardholder_last_name = sanitize($_POST['cardholder_last_name']);
$billing_address = sanitize($_POST['billing_address']);
$billing_address2 = sanitize($_POST['billing_address2']);
$billing_city = sanitize($_POST['billing_city']);
$billing_state = sanitize($_POST['billing_state']);
$billing_zip = sanitize($_POST['billing_zip']);
$telephone = sanitize($_POST['telephone']);
$email = sanitize($_POST['email']);
$account = sanitize($_POST['account']);
$amount = sanitize($_POST['amount']);
if (!validateCreditcard_number($credit_card))
{
$errors['credit_card'] = "Please enter a valid credit card number";
}
if (!validateCreditCardExpirationDate($expiration_month, $expiration_year))
{
$errors['expiration_month'] = "Please enter a valid exopiration date for your credit card";
}
if (!validateCVV($credit_card, $cvv))
{
$errors['cvv'] = "Please enter the security code (CVV number) for your credit card";
}
if (empty($cardholder_first_name))
{
$errors['cardholder_first_name'] = "Please provide the card holder's first name";
}
if (empty($cardholder_last_name))
{
$errors['cardholder_last_name'] = "Please provide the card holder's last name";
}
if (empty($billing_address))
{
$errors['billing_address'] = 'Please provide your billing address.';
}
if (empty($billing_city))
{
$errors['billing_city'] = 'Please provide the city of your billing address.';
}
if (empty($billing_state))
{
$errors['billing_state'] = 'Please provide the state for your billing address.';
}
if (!preg_match("/^\d{5}$/", $billing_zip))
{
$errors['billing_zip'] = 'Make sure your billing zip code is 5 digits.';
}
if (empty($telephone))
{
$errors['telephone'] = 'Please provide a telephone number where we can reach you if necessary.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$errors['email'] = 'Please provide a valid email address';
}
if (empty($account))
{
$errors['account'] = 'Please provide the Your Customer ID Number from your billing statement.';
}
if (empty($amount))
{
$errors['amount'] = 'Please enter a payment amount.';
}
// If there are no errors let's process the payment
if (count($errors) === 0)
{
// Format the expiration date
$expiration_date = sprintf("%04d-%02d", $expiration_year, $expiration_month);
// Include the SDK
require_once('./config.php');
// Process the transaction using the AIM API
$transaction = new AuthorizeNetAIM;
$transaction->setSandbox(AUTHORIZENET_SANDBOX);
$transaction->setFields(
array(
'amount' => $amount,
'card_num' => $credit_card,
'exp_date' => $expiration_date,
'first_name' => $cardholder_first_name,
'last_name' => $cardholder_last_name,
'address' => $billing_address,
'city' => $billing_city,
'state' => $billing_state,
'zip' => $billing_zip,
'email' => $email,
'card_code' => $cvv,
'Customer ID Number' => $account,
)
);
$response = $transaction->authorizeAndCapture();
if ($response->approved)
{
// Transaction approved. Collect pertinent transaction information for saving in the database.
$transaction_id = $response->transaction_id;
$authorization_code = $response->authorization_code;
$avs_response = $response->avs_response;
$cavv_response = $response->cavv_response;
// Put everything in a database for later review and order processing
// How you do this depends on how your application is designed
// and your business needs.
// Once we're finished let's redirect the user to a receipt page
header('Location: thank-you-page.php');
exit;
}
else if ($response->declined)
{
// Transaction declined. Set our error message.
$errors['declined'] = 'Your credit card was declined by your bank. Please try another form of payment.';
}
else
{
// And error has occurred. Set our error message.
$errors['error'] = 'We encountered an error while processing your payment. Your credit card was not charged. Please try again or contact customer service to place your order.';
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Payment Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Language" content="en-us">
<style type="text/css">
#errormessage
{
background-color: #FFE7E7;
border: 3px solid #CC0033;
color: #000000;
margin: 20px ;
padding: 10px;
width: 420px;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
-moz-box-shadow: 5px 5px 5px #ccc;
-webkit-box-shadow: 5px 5px 5px #ccc;
box-shadow: 5px 5px 5px #ccc;
background: -webkit-gradient(linear, 0 0, 0 bottom, from(#FFEAEA), to(#FFB3B3));
background: -moz-linear-gradient(#FFEAEA, #FFB3B3);
background: linear-gradient(#FFEAEA, #FFB3B3);
float: left;
}
.labelerror
{
color: #ff0000;
font-weight: bold;
}
h3 {
font-size: 1.6em;
line-height: 10px;
padding-left: 17px;
padding-top: 8px;
-webkit-font-smoothing: antialiased;;
}
#credit
{
Position: relative;
margin-left: 14px;
height:620px;
width:400px;
-webkit-border-radius: 6px;
border-radius: 6px;
-moz-box-shadow: 5px 5px 5px #ccc;
-webkit-box-shadow: 5px 5px 5px #ccc;
box-shadow: 5px 5px 5px #ccc;
float: left;
}
#amount1
{
margin: 5px;
height:620px;
position: relative;
width:400px;
-webkit-border-radius: 6px;
border-radius: 6px;
-moz-box-shadow: 5px 5px 5px #ccc;
-webkit-box-shadow: 5px 5px 5px #ccc;
box-shadow: 5px 5px 5px #ccc;
float: left;
}
</style>
</head>
<body>
<div id="amount1"> <h3> Payment Amount</h3><p>
<form id="myform"> <label for="amount"<?php if (in_array('amount', $errors)) echo ' class="labelerror"'; ?>> $</label>
<input type="text" name="amount" id="amount" maxlength="5" value=""></form>
</p> <br><div id="phpdisplay"> <form action="payment-form.php" method="get" enctype="application/x-www-form-urlencoded" target="_self" id="search">
<strong>Get your current balance by searching<br> your Customer ID number</strong><br>(Don't Know? Ask us on live chat or check your billing invoice):<br> <input type="text" name="term" /><br />
<input type="submit" name="btn" value="Search" />
</form>
</form></div>
<div id="credit">
<h3> Credit Card Information</h3>
<form id="myform" action="/payment-form.php" method="post">
<p>
<label for="credit_card"<?php if (in_array('credit_card', $errors)) echo ' class="labelerror"'; ?>>Credit Card Number</label>
<input type="text" name="credit_card" id="credit_card" autocomplete="off" maxlength="19" value="">
</p>
<p>
<label for="expiration_month"<?php if (in_array('expiration_month', $errors)) echo ' class="labelerror"'; ?>>Expiration Date</label>
<select name="expiration_month" id="expiration_month">
<option value="12">12</option>
</select>
<select name="expiration_year" id="expiration_year">
<option value="0"> </option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</p>
<p>
<label for="cvv"<?php if (in_array('cvv', $errors)) echo ' class="labelerror"'; ?>>Security Code</label>
<input type="text" name="cvv" id="cvv" autocomplete="off" value="" maxlength="4">
</p>
<p>
<label for="cardholder_first_name"<?php if (in_array('cardholder_first_name', $errors)) echo ' class="labelerror"'; ?>>Cardholder's First Name</label>
<input type="text" name="cardholder_first_name" id="cardholder_first_name" maxlength="30" value="">
</p>
<p>
<label for="cardholder_last_name"<?php if (in_array('cardholder_last_name', $errors)) echo ' class="labelerror"'; ?>>Cardholder's Last Name</label>
<input type="text" name="cardholder_last_name" id="cardholder_last_name" maxlength="30" value="">
</p>
<p>
<label for="billing_address"<?php if (in_array('billing_address', $errors)) echo ' class="labelerror"'; ?>>Billing Address</label>
<input type="text" name="billing_address" id="billing_address" maxlength="45" value="">
</p>
<p>
<label for="billing_address2"<?php if (in_array('billing_address2', $errors)) echo ' class="labelerror"'; ?>>Suite/Apt #</label>
<input type="text" name="billing_address2" id="billing_address2" maxlength="45" value="">
</p>
<p>
<label for="billing_city"<?php if (in_array('billing_city', $errors)) echo ' class="labelerror"'; ?>>City</label>
<input type="text" name="billing_city" id="billing_city" maxlength="25" value="">
</p>
<p>
<label for="billing_state"<?php if (in_array('billing_state', $errors)) echo ' class="labelerror"'; ?>>State</label>
<select id="billing_state" name="billing_state">
<option value="0"> </option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
</select>
</p>
<p>
<label for="billing_zip"<?php if (in_array('billing_zip', $errors)) echo ' class="labelerror"'; ?>>Zip Code</label>
<input type="text" name="billing_zip" id="billing_zip" maxlength="5" value="">
</p>
<p>
<label for="telephone"<?php if (in_array('telephone', $errors)) echo ' class="labelerror"'; ?>>Telephone Number</label>
<input type="text" name="telephone" id="telephone" maxlength="20" value="">
</p>
<p>
<label for="email"<?php if (in_array('email', $errors)) echo ' class="labelerror"'; ?>>Email Address</label>
<input type="text" name="email" id="email" maxlength="20" value="">
</p>
<p>
<label for="account"<?php if (in_array('account', $errors)) echo ' class="labelerror"'; ?>>Customer ID number</label>
<input type="text" name="account" id="account" maxlength="6" value="">
</p>
<p>
<input type="submit" value="Checkout">
</p>
</form></div><?php
if (count($errors))
{
?>
<div id="errormessage">
<h2>
There was an error with your submission. Please make the necessary corrections and try again.
</h2>
<ul>
<?php
foreach ($errors as $error)
{
?>
<li><?php echo $error; ?></li>
<?php
}
?>
</ul>
</div>
<?php
}
?>
</body>
</html>
Lastly, I wanted to move the checkout button outside the div form so I made the button like this(in the designed page, not the example above)
</form> <br>
<form id="myform"><p class="center">
<button form="myform" input type="submit" value="Checkout">
</p></form>
The button works but it's not displaying the value as the label on my (WIP) designed page.
This:
<button form="myform" input type="submit" value="Checkout">
is not how the <button> element is constructed. It looks like you attempted to change an <input />. This is likely what you're after:
<button form="myform" type="submit">Checkout</button>
It also looks like you're duplicating the id on two different forms, which is invalid. Remove the id on the form that wraps the submit button, or change it to something else.
This is actually several questions it seems to me. Since there's several, I might get something mixed up, someone point out if I get something blaringly wrong.
RE: ""amount" box actually recognize whether it's empty or filled." --
You can't split the amount off into it's own form and have it go along with the rest of the elements in the other form element. Everything you want to post has to be in the same form element. (Unless you use the html5 form attribute, but I don't think IE supports this yet. Someone correct me if I'm wrong please. Even then, you wouldn't be adding more form elements if I recall correctly.) See: Is it possible to wrap html form elements in multiple form tags? See the comments in the accepted answer for more details.
Regarding the boxes not changing with errors. --
<label for="billing_address2"<?php if (in_array('billing_address2', $errors)) echo ' class="labelerror"'; ?>>Suite/Apt #</label>
Should probably be:
<label for="billing_address2"<?php if (in_array('billing_address2', array_keys($errors))) echo ' class="labelerror"'; ?>>Suite/Apt #</label>
Your array is keyed with the element names, so your in_array should search the keys of the errors array. (Note that this will change the labels colors, not the input boxes themselves. Put the class-setting code on the boxes if you want the boxes themselves to change.)
Button is addressed in another answer:
<button form="myform" type="submit">Checkout</button>
HTML5 outside of form element. Again, not sure if IE supports this. No need to wrap it in a form element btw, assuming you're targeting browsers that support the form attribute.
<button type="submit">Checkout</button>
Inside form.

extra input added by jquery doesn't work

Hi I'm trying to get a dinamically input added with Jquery, but when I try to get the code it's not working
The code in codeigniter catch all POST but less the one added by jquery
here is the code:
<script type="text/javascript">
$(document).ready(function(){
var value = parseFloat($("#subtotal").val());
$('.subtotal').html(value);
$('#subtotal').val(value);
$('input[name="phprop"]').change(function(event){
if($('input[name="phprop"]:checked').val() == 'Yes'){
$('#sections').show();
}else if($('input[name="phprop"]:checked').val() == 'No'){ $('#sections').hide();}
});
$('input[name="xsst"]').change(function(event){
if($('input[name="xsst"]:checked').val() == 'Yes'){
$('#xtraphotos').show();
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo('#xtrabox');
var num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i); i++;
}else if($('input[name="xsst"]:checked').val() == 'No'){
$('#xtraphotos').hide();
$('#xtraphotos input[type="text"]').remove();
var num = value - 9.95 * (i - 1);
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(0);
i = 1;
}
});
var scntDiv = $('#xtrabox');
var i = 1;
$('#addScnt').live('click', function() {
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo(scntDiv);
num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i);
i++;
return false;
});
});
</script>
Here is the HTML
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
Here is the Codeigniter code:
if($_POST['extrass'] !=0){
for($i=1;$i<=$_POST['extrass'];$i++){
$names = "extraid".$i;
$extras .= $_POST[$names];
if($i!=$_POST['extrass']){
$extras .= "-";
}
}
Here is the complete HTML (Just the form Section):
<?php echo form_open_multipart(base_url() . 'purchase/confirmation')?>
<p style="float:left">Image ID of the Photos for your Website</p><div style="float:left;margin: 13px 0 0 110px;width: 450px;"><?php
if($idtype == 4){$x=3;}elseif($idtype == 1){$x=5;}elseif($idtype == 2){$x=10;}elseif($idtype == 3){$x=13;}
for($i=1;$i<=$x;$i++){?><input type="text" name="ssid[]" id="ssid_<?=$i?>" value="" style="width:80px; margin-left:4px;"/><?php }?></div>
</div>
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
<br />
<div id="choose_your_template" style="background-image:url(<?=base_url()?>images/step_4.png)"><div style="padding-left:5px; float:left">
<span style=" position: relative; top: 14px; left: 210px; font-size: 18px; color: gray; ">Step 4: Do you have Photos? Upload the pictures for your website.</span></div>
</div>
<div style="margin-left: 50px;">
<label>Do you have photos of your property? </label>Yes<input type="radio" name="phprop" id="phprop" value="Yes"/>No<input type="radio" name="phprop" id="phprop" value="No"/><br />
<div id="sections" style="display:none;">
<p>Upload the photos in the theme that they should be used. The photos should be in jpge.format. Otherwise the system will not accept. them.</p><br/>
<?php
if($idtype == 4){$x=1;}elseif($idtype == 1){$x=3;}elseif($idtype == 2){$x=4;}elseif($idtype == 3){$x=5;}
for($i=1;$i<=$x;$i++){?>
<label>Section</label><select name="section[]" id="section"><option value="">Choose Section</option><option value="home">Home</option><option value="about-us">About Us</option><option value="contact-us">Contact Us</option></select><?php for($j=1;$j<=4;$j++){?><input type="file" name="userphoto<?=$i?><?=$j?>" /><?php }?><br /> <br />
<?php }?>
<p>I certify that the photos that i am uploading for the website development are of my entire property and that I have all the copyrights.</p></div>
</div><br />
<input type="hidden" id="domain" name="domain" value="<?=$domain?>" />
<input type="hidden" id="payment_plan" name="payment_plan" value="<?=$poption?>" />
<?php if($ownamedomain){?>
<input type="hidden" name="ownamedomain" id="ownamedomain" value="<?=$ownamedomain?>" />
<?php }?>
<input type="hidden" name="idtype" id="idtype" value="<?=$idtype?>" />
<input type="hidden" name="templateid" id="templateid" value="<?=$templateid?>" />
<input type="hidden" name="extrass" id="extrass" value="0" />
<input type="hidden" name="subtotal" id="subtotal" value="<?=$subtotal?>" />
<div style="padding-left:45px; padding-top:15px;">
<hr style=" width: 868px; margin: 0 0 16px; "/>
<div align="center">
<p>Subtotal: USD$<span class="subtotal"><?=$subtotal?></span> </p></div>
</div>
<div style="background:url(<?=base_url()?>images/bottombar.png) no-repeat;display: block;height: 16px;margin: 0 36px 10px;width: 902px;"></div>
<input type="submit" name="continue" id="continue"/><input type="button" value="Back" onClick="history.back();" class="back">
</div>
Your HTML have a tag form?
When.you not put forms elements inside a form, onload, some brownser add a form to correct code syntax... But when you add nes elements using DOM, maybe this elements not include inside this form...

HTML forms, add area on click

I'm not sure how to ask what I'm looking for to search how-tos. I am building a form and one of the entries requires users to list an appliance, its voltage, watts, amps, phase, etc.
I'd like a simple row with "X" columns providing the text areas for one appliance and then the ability to click a link to 'add another appliance' using jquery/html.
I like using placeholder text to save space on the page. I can get all this set up just fine for a single entry like 'name' however I don't know how to implement an 'add entry' row. All of the data is stored via PHP in MySQL.
So A: What is the name of this type of form section. B: What is it called when we want to let the user add a row to this section?
I love making things harder than they really are. It's my specialty. I guess :)
EDIT: http://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit
Using this format with 5 columns per entry (though it will all be on one line/row) I'd like to have an "add entry" link which generates a new blank entry option.
#elecNeeds input[type=text], textarea {
font-size: 12px;
font-style: italic;
width: 15%;
height: 20px;
padding: 10px;
color: #212323;
background: #E3E3E3;
background: rgba(255, 255, 255, 0.5);
border: 2px #000 solid;
margin-bottom: 10px;
position: relative;
behavior: url(/js/PIE.htc);
}
<div id="elecNeeds">
<input type="text" name="appliance" placeholder="Type of Equipment">
<input type="text" name="voltage" placeholder="Voltage">
<input type="text" name="watts" placeholder="Watts">
<input type="text" name="amps" placeholder="Phase">
<input type="text" name="notes" placeholder="Notes">
<br /> Add an appliance
</div>
I don't know what's it called, but you probably want this - http://jsfiddle.net/uPWkf/1/
<form method="post" action="#" id="myForm">
<div id="nameFields">
<label>Watt <input type="text" name="watt0" /></label>
<label>Volt <input type="text" name="volt0" /></label>
<label>Amp <input type="text" name="amp0" /></label><br/><br />
</div>
<input type="submit" value="submit" id="submit" />
</form>
Add New Row
and the JS
var i = 1;
$("#addRow").click(function() {
$("#nameFields").append('<label>Watt <input type="text" name="watt' + i + '" /></label><label>Volt <input type="text" name="volt' + i + '" /></label><label>Amp <input type="text" name="amp' + i + '" /></label><br/><br />');
i++;
});
$('#myForm').submit(function() {
var values = $('#myForm').serialize();
alert(values);
});
I think You need to use $(selector).append('<code>'); function. For example:
Add
<table class="my_fuits">
<tr>
<td>Fruit</td>
<td><input type="text" name="fuits[]" /></td>
</tr>
</table>
and js(jQuery) code:
$(document).ready(function(){
// add one more row
$(".add").live('click',function(){
$(".my_fuits").append('<tr><td>Fruit '+$(".my_fruits input").length+'</td><td><input type="text" name="fuits[]" />[X]</td></tr>');
return false;
});
// remove row
$(".remove").live('click',function(){
$(this).parent().parent().remove();
return false;
});
});

Tell me there's a better way to turn these checkboxes into JSON

I'm working on a form that lets folks choose their preferred methods of contact. Among other things, the form consists of 9 checkboxes (3 sets of three) that I'm trying to store in my database as JSON.
Here's the pertinent parts of the form...
<h1 style="padding-top:25px;">Communication Preferences</h1><hr />
<div class="onethird contactprefs" style="width: 28%">
<h4>Preferred Method</h4>
<p>From time to time, we might need to contact you regarding our service. Which mode of contact would you prefer?</p>
<p>
<input type="checkbox" name="preferred[]" value="p" style="display: inline;" />Phone <!-- make these tooltips -->
<br />
<input type="checkbox" name="preferred[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="preferred[]" value="s" style="display: inline;" />SMS
</p>
</div>
<div class="onethird contactprefs" style="width: 28%; border-left: solid 1px #cdcdcd; border-right: solid 1px #cdcdcd; padding-left: 18px; padding-right: 15px;">
<h4>Weather Delays</h4>
<p>We don't mess with Mother Nature, and sometimes she forces us to cancel service. If that happens, how should we inform you?</p>
<p>
<input type="checkbox" name="weather[]" value="p" style="display: inline;" />Phone
<br />
<input type="checkbox" name="weather[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="weather[]" value="s" style="display: inline;" />SMS
</p>
</div>
<div class="onethird contactprefs" style="width: 28%">
<h4>Holiday Reminders</h4>
<p>If you'd like us to send you reminders about interruptions in service due to holidays, just choose your preferred method below.</p>
<p>
<input type="checkbox" name="holiday[]" value="p" style="display: inline;" />Phone
<br />
<input type="checkbox" name="holiday[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="holiday[]" value="s" style="display: inline;" />SMS
</p>
</div>
<!-- end contact preferences -->
As I mentioned, I need to take the data from these checkboxes and convert them into a well formed JSON string.
Here's what I'm doing, but it seems awfully messy. Tell me theres a better way...
/* THERE MUST BE A BETTER WAY TO DO THIS */
// get the preferred data
$preferred = $this->input->post('preferred');
if(in_array('p',$preferred)){
$pref['p'] = 1;
}else{ $pref['p'] = 0;}
if(in_array('e',$preferred)){
$pref['e'] = 1;
}else{ $pref['e'] = 0;}
if(in_array('s',$preferred)){
$pref['s'] = 1;
}else{ $pref['s'] = 0;}
// get the weather data
$weather = $this->input->post('weather');
if(in_array('p',$weather)){
$wea['p'] = 1;
}else{ $wea['p'] = 0;}
if(in_array('e',$weather)){
$wea['e'] = 1;
}else{ $wea['e'] = 0;}
if(in_array('s',$weather)){
$wea['s'] = 1;
}else{ $wea['s'] = 0;}
// get the holiday data
$holiday = $this->input->post('holiday');
if(in_array('p',$holiday)){
$hol['p'] = 1;
}else{ $hol['p'] = 0;}
if(in_array('e',$holiday)){
$hol['e'] = 1;
}else{ $hol['e'] = 0;}
if(in_array('s',$holiday)){
$hol['s'] = 1;
}else{ $hol['s'] = 0;}
$contact_prefs = array('preferred' => $pref,'weather' => $wea,'holiday' => $hol);
$contact_prefs = json_encode($contact_prefs);
Thanks in advance for the insight.
One idea to make it more automatic (untested):
$contact_prefs = array();
$groups = array('preferred', 'weather', 'holiday'); // checkbox groups
foreach($groups as $group) {
$preferences = array('p' => 0, 'e' => 0, 's' => 0); // create default array
$values = $this->input->post($group); // get the checked values for a group
foreach($values as $value) {
$preferences[$value] = 1; // if box is checked, set value to 1
}
$contact_prefs[$group] = $preferences;
}
$contact_prefs = json_encode($contact_prefs);
Of course this only works, if the three checkbox groups have the same values.

Categories