Calculating total in PHP - php

I have my form done but I am trying to create a handling form which calculates the total plus shipping of $5 and 8% tax rate and displays it.
Need a handling form for my following PHP code. The handling form should calculate total price, 8%tax, $5 shipping fee. It should say thank you for ordering (name entered in form) on (date entered in form)
Need a handling form for my following PHP code. The handling form should calculate total price, 8%tax, $5 shipping fee. It should say thank you for ordering (name entered in form) on (date entered in form)
<html
<head>
</head>
<body>
<link rel= "stylesheet" href= "order.css">
<form action="complete.php" method="post">
<form name="order">
<fieldset><legend>Complete Order:</legend>
<h1> Choose Design </h1>
<p><label>Your Name: <input type="text" name="name"></label>
<label>Address: <input type="text" name="address"></label>
<label>Credit Card #: <input type="text" name="creditcard"></label>
<label>Date: <input type="date" id="datepicker" name='date' size='9' value="" > </label>
<br><label> Design Types: <img src="1.jpg"><input type="checkbox" name="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="2"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="3"> </label>$1.00
<br></p>
<input type="submit" value="Submit Order">
</form>
</body>
</html>

This is the handler, but before I start on the answer. I just wish to make it clear that Stack Overflow is a Q&A environment and not a place for someone to do your work. That being said, I have answered this question...
Place this code at the top of the HTML page that I will post (I have made some amendments).
Note the $date variable uses the ternary operator to ensure a date will get posted to the database. I have formatted the date in the yyyy-mm-dd format which is the format of MySQL databases (I'm not sure about the format the others use, but I imagine it is the same).
<?php
// only run if form is posted
if (isset($_POST["submit"]))
{
// set POST to variables (easy to type variable name)
$name = $_POST["name"];
$address = $_POST["address"];
$creditcard = $_POST["creditcard"];
$date = $_POST["date"] == "" ? date("Y-m-d") : $_POST["date"];
$design = $_POST["designType"];
$total = $design; // add the cost of design
$total += $total * 1.08; // work out tax
$total += 5; // the shipping fee
}
?>
I have made a few changes to the form that you posted. Here they are:
I indented the tags (it's a personal preference but I think it makes it look neater)
Added </fieldset> to the end of the form. This ensures it passes W3C Validator which requires closing of tags
I changed the checkboxes to radio types. This was an assumption based on how I thought you form was supposed to be (I wasn't sure where total was coming from otherwise; so I assumed the "Design type" was the price)
I reformatted the <label> and <input> so that they weren't nested (with the exception of radio elements, but that is so you can click the label to select the radio)
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<link rel="stylesheet" href="order.css" />
</head>
<body>
<?php if (isset($_POST["submit"])) { ?><div id="message">Thank you, <?php echo $name; ?> for ordering on <?php echo $date; ?>. The total was <?php echo "$" . number_format($total, 2); ?> </div><?php } ?>
<form name="order" action="complete.php" method="post">
<fieldset>
<legend>Complete Order:</legend>
<h1>Choose Design</h1>
<label>Your Name:</label><input type="text" name="name" />
<label>Address:</label><input type="text" name="address" />
<label>Credit Card #:</label><input type="text" name="creditcard" />
<label>Date:</label><input type="date" id="datepicker" name='date' size='9' value="" />
<br />
<label>Design Types:</label>
<label><img src="1.jpg" alt="$1.00" /><input type="radio" name="designType" value="1" />$1.00</label>
<label><img src="2.jpg" alt="$2.00" /><input type="radio" name="designType" value="2" />$2.00</label>
<label><img src="3.jpg" alt="$3.00" /><input type="radio" name="designType" value="3" />$3.00</label>
<br />
<input type="submit" name="submit" value="Submit Order" />
</fieldset>
</form>
</body>
</html>
That is all.
Again, let me reinforce the idea that Stack Overflow is not here for this type of "question". Please also provide an attempt at your problem as well.

Related

Placing data in MySQL database from form fields created on the fly

I have a form that allows members to click a (+) sign, and it will put another form field there. They can do this to basically without limit.
The problem I have is if they do it, let's say, 3 times and fill out all 3, when I get the data to save it, it's placing the first field in the database and not the others.
Here is my code:
Here is the JavaScript that makes the div show as they push the (+) sign.
<script type="text/javascript">
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
document.getElementById('newlink').appendChild(div1);
}
</script>
<style>
.feed {padding: 5px 0}
</style>
This is part of the form that does the above...
<td width="50%" valign="top">
<div id="newlink">
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
<hr>
<p id="addnew">
+ Click Here To Add Another Biz/Traffic/Tools Site
</p>
<div id="newlinktpl" style="display:none">
<hr>
<div class="feed">
<input type="text" size="45" value="" name="recname[]" placeholder="Place Company Name Here"><br /><br />
<input type="text" size="45" value="" name="reclink[]" placeholder="Place URL Here"><br /><br />
<p><b>What Type Of Page Is This?</b><br /><br />
<input type="radio" name="rectype[]" value="1"> Business Opp<br />
<input type="radio" name="rectype[]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[]" value="3"> Tools Site<br /></p>
</div>
</div>
This is the part of the PHP code that would save it...
$i=0;
$linkname = $_POST["recname"][0];
while($linkname != ""){
$linkname = $_POST["recname"][$i];
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
$linkname = $res->real_escape_string($linkname);
$linkurl = $res->real_escape_string($linkurl);
$linktype = $res->real_escape_string($linktype);
$result299 = mysqli_query($res, "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')");
$i++;
}
It's all working except that is does not store all the data in the database (only the first one saves). That's the part I need help with please.
Please explain what I have done wrong and how to get it to store all the fields in the database, no matter how many the user creates and fills out.
I tested your code and it works fine so far if I use it like this:
$i=0;
$linkname = $_POST[recname][0];
while($linkname != ""){
$linkname = $_POST[recname][$i];
$linkurl = $_POST[reclink][$i];
$linktype = $_POST[rectype][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
There's no information about the $res object you're calling real_escape_string() on, so I'll just skip that for now. There are a couple of weaknesses in the code though:
You are referencing the post keys with barenames instead of strings.
PHP will gracefully assume you meant it as a string, but it will trigger a notice like Use of undefined constant recname - assumed 'recname'. Enclose them in quotes to make it clean.
Your use of the loop will result in an empty element inserted in the database every time.
You set the new linkname AFTER checking if $linkname is empty, but the variable contains the name of the last iteration. Instead, do something like this:
$i=0;
while($linkname = $_POST["recname"][$i]){
$linkurl = $_POST["reclink"][$i];
$linktype = $_POST["rectype"][$i];
echo "INSERT INTO user_links (linkname,linkurl,linktype,sort) VALUES ('$linkname','$linkurl','$linktype','0')<br>\n";
$i++;
}
Your code only allows for one radio button to be checked at a time
You cannot use rectype[] as a name for radio buttons, as an equal name forms a group of radio buttons out of all the elements. You need to name them like this:
<input type="radio" name="rectype[0]" value="1"> Business Opp<br />
<input type="radio" name="rectype[0]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[0]" value="3"> Tools Site<br />
<input type="radio" name="rectype[1]" value="1"> Business Opp<br />
<input type="radio" name="rectype[1]" value="2"> Traffic Site<br />
<input type="radio" name="rectype[1]" value="3"> Tools Site<br />
and so on. You can do that programatically in your javascript code like this:
<script type="text/javascript">
var counter = 1;
function add_feed()
{
var div1 = document.createElement('div');
div1.innerHTML = document.getElementById('newlinktpl').innerHTML;
var inputs = div1.getElementsByTagName('input');
for (i=0; i<inputs.length; i++) {
if (inputs[i].type == "radio") {
inputs[i].name="rectype[" + counter + "]";
}
}
counter++;
document.getElementById('newlink').appendChild(div1);
}
</script>
That said, I don't see why it should only save one item, unless you have a key constraint hitting or something else we cannot assume from the piece of code you shared.

Why are the nested forms processed with $_SERVER['PHP_SELF'] (same html file) not displaying/processing correctly?

I'm trying to get user input in a progressive sequence that leads to that input being sent by email. Sending by email is a whole other issue that I haven't tackled yet so not really worried about that.
The part I am having difficulty with is once the user gets to the "Send Email?" (Yes/No) radio buttons, the input from that question is not processed correctly.
I've gotten further with this by using a separate php file as the form action but still get errors related to emailName, emailAddress, and emailMsg not existing ("Notice: Undefined index...").
Furthermore, I still need to be able to use the $_POST[athletes] array further down but I'm guessing it's outside of the variable scope at that point.
So to bring that all together, I'm really asking a few questions:
1) How can I get all of the forms to work together in the same file?
2) When the program actually goes past the "Send Email?" radio buttons when I use a separate php file as the form action, why am I getting undefined index errors?
3) Why do I get an error when I try to use the athletes[] array further down in the code? Should I somehow be passing the array values to that part of the code?
The exact steps the user would take to get to the issue is:
Select 1 or more athlete checkboxes and click the 'Display Selection(s)' button.
Select 'Yes' for "Send Email?" and click the 'Submit' button.
Restarts the code for some reason.
Any help would be greatly appreciated. Also, this is my first post so sorry if I asked the question incorrectly or not according to site etiquette.
I also apologize for the long code fragment but I'm not sure what parts might be causing this to be incorrect.
<b><h1><center>Athelete Selection Screen</center></h1></b>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Athletes Available: </legend>
<input type="checkbox" id="student1"
name="athletes[]" value="Student1 Test">
<label for="student1">Student1 Test</label><br/>
<font color="grey">Football - Running back</font><br/>
<p>
<input type="checkbox" id="student2"
name="athletes[]" value="Student2 Test">
<label for="student1">Student2 Test</label><br/>
<font color="grey">Soccer - Left Forward</font><br/>
</p>
<p>
<input type="checkbox" id="student3"
name="athletes[]" value="Student3 Test">
<label for="student1">Student3 Test</label><br/>
<font color="grey">Baseball - Pitcher/Left Outfield</font><br/>
</p>
</fieldset>
<p>
<?php echo("\t\t\t\t\t"); ?><button type="submit" name="submit" value="submit">Display Selection(s)</button>
</p>
</form>
<fieldset>
<legend>Athletes You Selected: </legend>
<?php
if (!empty($_POST['athletes']))
{
echo "<ul>";
foreach($_POST['athletes'] as $value)
{
echo "<li>$value</li>";
}
echo "</ul>";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<fieldset>
<legend>Send Email? </legend>
<input type="radio" id="Yes"
name="radioSendMsg[]" value="Yes">
<label for="student1">Yes</label>
<p>
<input type="radio" id="No"
name="radioSendMsg[]" value="No">
<label for="student1">No</label><br/>
</p>
<button type="submit" name="submitRadio" value="submit">Submit</button>
</p>
</form>
<?php
if (!empty($_POST['radioSendMsg']))
{
foreach($_POST['radioSendMsg'] as $radioMsg)
{
if($radioMsg == "Yes")
{
echo "\tPlease enter information regarding the email to be sent: ";
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>
<label for="emailName"> Name: </label><br/>
<input type="text" size="25" id="emailName" name="emailName" />
</p>
<p>
<label for="emailAddress">E-mail Address: </label></br>
<input type="text" size="25" id="emailAddress" name="emailAddress" />
</p>
<p>
<textarea id="emailMsg" name="emailMsg" cols="30" rows="5"></textarea>
</p>
<button type="submit" name="emailSubmit" value="send">Send Message</button>
</form>
<?php
$msg = "Name: ".$_POST['emailName']."\n";
$msg.= "E-Mail: ".$_POST['emailAddress']."\n";
$msg.= "Message: ".$_POST['emailMsg']."\n";
$msg.= "<ul>";
foreach($_POST['athletes'] as $value)
{
$msg.= "<li>$value</li>\n";
}
$msg.= "</ul>";
$emailRecipient = "sjzerbib#gmail.com";
$emailSubject = "Athlete Selection Submission";
$emailHeaders = "From: Sebastien\n"."Reply-To: ".$_POST['emailAddress'];
mail($emailRecipient,$emailSubject,$msg,$emailHeaders);
echo "Message sent: \n".$msg;
}
else
{
?> <p /> <?php
echo "\n\nNo email will be sent for your last athlete selection.";
?>
<br/>Please click here
to return to the Athlete selection screen.
<?php
}
}
}
}
When you submit a form, only those controls contained within that form are included. The exception is successful controls that have the form attribute set to the id value of the form that was submitted.
So, given you had something like:
<form id="form-1" method="post">
<input type="text" name="first-input" />
</form>
<input type="text" name="second-input" />
The only value to be submitted would be that of first-input. If you add the form attribute to second-input:
<input type="text" name="second-input" form="form-1" />
Then the submission of the form would include both values. Unfortunately, the form attribute is not fully supported (IE and Edge have no support).
Of course, your markup is invalid, so that's a moot point. For starters, you cannot nest a form within a form. How a browser responds to markup that violates that rule is up to it's vendor, but in my experience is somewhat unpredictable. You're also using deprecated tags (<font> and <center> are no longer valid) and nesting elements incorrectly (<h1> is a block level element, whereas <b> is inline).
If you're doing a full submit each time (so the page gets submitted to itself and then reloads), then just use some sort of conditional to only render the dependent controls if the preceding form submissions were successful:
<?php
$canDoNextStep = !empty($_POST['input-1']);
?>
<form id="form-1" method="post">
<input type="text" name="first-input" />
<?php if(canDoNextStep): ?>
<input type="text" name="second-input" />
<?php endif; ?>
</form>
Lastly, whitespace is (mostly) ignored when your browser parses and displays your HTML, so you can lose the \t and \n values in your strings, unless you're concerned about how your markup looks if someone chooses to view source when using your form.

Can't make Item name appear when going to different page

I am making a store for a school project and I am having a hard time making text of the item name and price be saved in a variable then shown on the checkout page.
My code for the item description looks like this:
<div id="section">
<img src="http://ecx.images-amazon.com/images/I/71nodfoCvyL._SL1500_.jpg" alt="HTML tutorial" style="width:152px;height:172px;border:0;" align="right">
<?php $item->name='ASUS M32CD Desktop'; $item->price='549.99'; $i++; ?>
<h4>ASUS M32CD Desktop</h4>
<h6> $549.99 </h6>
<br>
<input type="checkbox" name="item<?php echo $i; ?>" value="<?php echo $item->name.'#'.$item->price; ?>">
Buy
When I select it and press purchase, it takes me to the checkout page but doesn't have the items listed. My checkout page looks like this:
<!DOCTYPE html>
<!-- HardDrive1.html -->
<!-- Jan 22, 2016 -->
<html>
<head>
<title>Order Form</title>
</head>
<body>
<h3>Please Input All Information to Complete Your Order</h3>
<?php echo $item->name; ?>
<?php echo $item->price; ?>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value=""><br>
Last name:<br>
<input type="text" name="lastname" value=""><br>
Street Address:<br>
<input type="text" name="address" value=""><br>
City:<br>
<input type="text" name="city" value=""><br>
You can avhieve what you want, catch a shopping basket in three ways:
1) Server side, on a SESSION, so once the user selects an item it must be stored in a SESSION, with its quantity. I don't recommend to store prices on it, they shall be fetched from a data source in order to prevent user manipulation of forms.
$_SESSION['cart']['item']=$_POST['item_name']
$_SESSION['cart']['item_quantity']=$_POST['item_quantity']
2). Client side, on local Storage API, using Javascript.
localStorage.setItem("item", "ASUS M32CD DESKTOP");
3) Less recommended to store on a cookie, is a file created by the server and deployed on user's hard disk and accessed only by your server.

How do I determine which dynamically-generated submit button was clicked in my PHP form?

I want to edit a dynamically-generated form (meaning: I don't know how many rows will be generated). This content is generated within a while loop, and the HTML generated has creates buttons of input-type=submit, generating as many identically-named buttons as there are iterations in the loop.
Of the generated buttons, I want to know which submit button has been clicked, in order to provide the user the same form for which it has been clicked. Disregard the name of the database and password to connect it; the connectivity is fine.
Feel free to suggest any new method to achieve the desired functionality.
The code is as follows:
echo "you have reached your travel details page. your recent travelling details are as follows".'</br>';
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE emailid='{$_SESSION['username']}' ORDER BY dep_date DESC";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
?>
<h1>Your travel details are:-</h1>
<form name="showtraveldet" METHOD="POST" action="edittraveldet.php">
<table border="1">
<tr>
<th>Starting point</th><th>Ending point</th><th>No of passengers</th><th>Expected fare</th><th>Departure date</th>
<th>Departure time</th><th>Arrival Date</th><th>Arrival Time</th><th>Car Model</th><th>Car number</th>
<th>Who is driving</th><th>Driver's license number</th>
</tr>
<?php
while ($row=mysqli_fetch_array($result))
{
$tid=$row['travel_id'];
echo "the value of tid is '{$tid}'";
echo'<tr><td>'.$row['start_point'].'</td><td>'.$row['end_point'].'</td><td>'.$row['no_of_pass'].'</td><td>'.
$row['exp_fare'].'</td><td>'.$row['dep_date'].'</td><td>'.$row['dep_time'].'</td><td>'.$row['arr_date'].'</td><td>'.$row['arr_time'].'
</td><td>'.$row['car_model'].'</td><td>'.$row['car_no'].'</td><td>'.$row['who_is_driving'].'</td><td>'.$row['driver_license_no'].'</td>
<td><input type="submit" name="edit" value="Edit"></td></tr><input type="hidden" name="travelid" value="'.$row['travel_id'].' ;?>">';
}
edittraveldet.php :-
$travelid=$_POST['travelid'];
echo "the travel id in the variable is $travelid and got the value from '{$_POST['travelid']}'";
$dbc=mysqli_connect('localhost','xyz','xyz','abc') or die("connection to DB failed");
$query="SELECT * FROM travel_details WHERE travel_id='{$travelid}'";
$result=mysqli_query($dbc,$query) or die("error in querying the DB");
mysqli_close($dbc);
$row=mysqli_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validatewheregoing()" name="wheregoing">
<h1> Enter your travelling details so that other travellers can join you</h1>
<fieldset>
<legend> Travelling details </legend>
Start Point: <input type="text" name="start" value="<?php echo $row['start_point']; ?>"/><br />
End point: <input type="text" name="end" value="<?php echo $row['end_point']; ?>"/><br />
Passengers allowed: <input type="number" name="noofpass" value="<?php echo $row['no_of_pass']; ?>"/><br />
Expected Fare per passengers in rupees:<input type="number" name="fare" value="<?php echo $row['exp_fare']; ?>"/><br />
Departure Date:<input type="date" name="depdate" value="<?php echo $row['dep_date']; ?>"/><br/>
Departure time:<input type="time" name="deptime" value="<?php echo $row['dep_time'] ;?>"/><br/>
Arrival Date:<input type="date" name="arrdate" value="<?php echo $row['arr_date']; ?>"/><br/>
Arrival time at destination:<input type="time" name="arrtime" value="<?php echo $row['arr_time']; ?>"/><br/>
Car Model and name:<input type="text" name="cardet" value="<?php echo $row['car_det']; ?>"/><br/> <!--make this as a dropdown box for better database matching-->
Car Number:<input type="text" name="carno" /><br/><input type="checkbox" name="taxi" value="check this box if pooling a taxi">
Is the car self driven or driven by driver?<input type="radio" name="drivedet" value="Selfdriven" checked=""/>Self Driven<input type="radio" name="drivedet" value="driverdriven" />Driver driven<br />
Driver's License number<input type="text" name="licence_no"/></br>
<input type="checkbox" name="taxi" value="check this box if pooling a taxi"></br>
<input type="hidden" name="travelid" value="<?php echo $travelid ;?>" />
<input type="submit" value="invite travellers" name="editwheregoing"/>
</fieldset>
</form>
If only you can change your code, I would suggest you put the form tag itself in the while loop, each having the same action pointing to the same url but submitting different information to the destination page. This way you don't have to worry about the button clicked
while($row=mysqli_fetch_array($result))
{
//<form action="sameactionurl.php" name="form_1">
//<input type="hidden" name="travelid" value="$row['travelid']" />
//</form>
}
Another solution, if you don't want to change your code is use JavaScript to set a common hidden field to the value of the current ID before submitting the form
Name your submit buttons in a standard fashion and append a 3-digit number to the end, "button_XXXX_###" where ### is the number and XXX was the original name of your button.
After submission, check your request parameters for all variables starting with name "button_XXXX", and split the actual name "button_XXXX_####" by '_' character, and the "###" suffix will reveal the number of the button pressed.
It might be easier to create a form for each row instead, though.

PHP code inside javascript

I have no idea about how javascript works, but I was able to write the following code by copying from different sites.
My aim is to have 2 radio boxes (1 = India, 2 = Other than India) and if Other than India is selected, then a dropdown box is displayed which shows names of all countries.
The dropdown is selected from a database and it is achieved by a custom php function.
I am able to make the code display the dropdown based on my radio box selection.
What I am unable to do is as follows:
I am not able to select any values from the dropdown.
I'm not able to make the dropdown hide if I change the choice in the radio box
Here is the code of the form:
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<fieldset>
<br />
<script type="text/javascript">
function onclickradio(entry){
if (entry === true) {
alert("YOU HAVE CHOSEN INDIA");
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '</br><?php dropdown('country');?>';
}
}
</script>
Country: </br>
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="INDIA" name="country" type="radio" checked="checked"/> INDIA
<input onclick="onclickradio(document.getElementById('INDIA').checked);" id="OTHER THAN INDIA" name="country" type="radio"/> OTHER THAN INDIA
<br /><br /><br />
State: <input type="text" name="State" maxlength="30"/><br />
Line1: <input type="text" name="Line1" maxlength="50" /><br />
Line2: <input type="text" name="Line2" maxlength="50" /><br />
City: <input type="text" name="City" maxlength="40" /><br />
PIN Code: <input type="text" name="PIN_Code" maxlength="8" /><br />
<input type="submit" name="submit_address" value="Submit Address" />
</fieldset>
</form>
Here is the code for the custom PHP dropdown function:
<?php
function dropdown($tablename) /*remember to add single quote around the input*/
{
$sql="SELECT * FROM ".$tablename;
$result=mysqli_query($GLOBALS["connection"], $sql)
or die('Error in running SELECT query');
$options=""; //initialising the variable, so that it can be concatenated later
while ($row=mysqli_fetch_array($result))
{
$x=0; /*$x is the index of the field in a row (it has to start with $x=0;
because the first index is 0 in php*/
$rowstr=" # "; /*initialising the variable,
so that it can be concatenated later*/
while ($x+1<=mysqli_num_fields($result)) /*mysqli_num_fields gives the actual number of fields, and not the index.
Since the index starts with 0, it is to be incremented by 1
before comparison with the mysqli_num_fields*/
{
$rowstr.= $row[$x]." # "; //concatenation operator
$x=$x+1;
}
$options.="<option value=".$rowstr.">".$rowstr."</option>"; //concatenation operator
}
Echo "<select>".$options."</select>";
}
?>
A few things that come to mind:
Don't put spaces in id values. I recommend that you use lower case as well, so you could have "india" and "not-india" instead.
Use Firefox/Firebug or similar to see if you have any JavaScript errors when you run this
Consider using jQuery or similar to catch change events - it is easy to use and uses the 'unobtrusive' method of adding JS functionality to your page.
Id field of an element can not have space. Just try removing spaces in "OTHER THAN INDIA" or replace to looks like OTHER_THAN_INDIA
Try this:
$(document).ready(function() {
// hide address inputs
$('#address').hide();
// show address inputs if the not india button is pressed
$('#not-india').click(function() {
$('#address').show();
});
// re-hide address inputs if india is selected
$('#india').click(function() {
$('#address').hide();
});
});
You will also have to include jQuery in your page.
Fiddle: http://jsfiddle.net/EN4jB/6/
Please note that I used the following markup - particular attention is due to the id of this div.
<input id="india" name="country" type="radio" checked="checked"/> India
<input id="not-india" name="country" type="radio" /> Not India
<br />
<div id="address">
<p><select>
<option>USA</option>
<option>UK</option>
<option>Ireland</option>
<option>etc...</option>
</select>
</p>
<p>State: <input type="text" name="State" maxlength="30"/></p>
<p>Line1: <input type="text" name="Line1" maxlength="50" /></p>
<p>Line2: <input type="text" name="Line2" maxlength="50" /></p>
<p>City: <input type="text" name="City" maxlength="40" /></p>
</div>
To clear the selection if India is chosen
function onclickradio(entry) {
if(entry===true) {
alert("YOU HAVE CHOSEN INDIA");
document.getElementById('OTHER THAN INDIA').innerHTML = '';
}
else {
document.getElementById('OTHER THAN INDIA').innerHTML = '<br/><?php dropdown('country');?>';
}
}

Categories