Jquery change textbox values dynamically on Change after table row clone - php

I have a sort of complex php,html script that I am using to create an interactive design. I am using a repeat table and i am basically cloning the contents of a particular table row and appending it to the end of the table. When I select a certain option in the select menu, the corresponding textfields get updated with the correct values. However cloned rows misbehave
What I'm asking is if there is a way to make this fields also change values. Here is the various code
Code for adding/cloning a row. Please note the id details is the id of a table row
$("#addrow1").click(function(){
//alert("It works");
//$('#description tr:last').after('<tr>...</tr>');
$('#details').clone().appendTo('#dailyexpense');
});
Code for changing the textfield and textbox values
$("#cities").live('change',function(){
var cityrates = $("#cities :selected").val();
var brkfstrates = (0.2 * cityrates).toFixed(1);
$("#brkfasttxt").val(brkfstrates);
$("#brkfastchk").val(brkfstrates);
var lunchrates = (0.3 * cityrates).toFixed(1);
$("#lunchtxt").val(lunchrates);
$("#lunchchk").val(lunchrates);
var dinnerrates = (0.3 * cityrates).toFixed(1);
$("#dinnertxt").val(dinnerrates);
$("#dinnerchk").val(dinnerrates);
var incdntlrates = (0.2 * cityrates).toFixed(1);
$("#incidentltxt").val(incdntlrates);
$("#incidentlchk").val(incdntlrates);
});
My table row code for the one that gets loaded by the browser
<tr id="details">
<td><label for="date"></label>
<input style="background-color:#CCC;" type="text" name="date" id="date" /></td>
<td><label for="cities"></label>
<select name="cities" id="cities" style="background-color:#CCC; width:220px;">
<?php
foreach($country as $makassi1){
$selectcities = "SELECT City, Country, Rate FROM perdiem_rates WHERE Country = '$makassi1'";
$checkcity = mysql_query($selectcities)or die(mysql_error());
$countcities = mysql_num_rows($checkcity);
while($row=mysql_fetch_assoc($checkcity))
{
$countries = ($row['Country']);
$names =($row['City']) ;
$rate =($row['Rate']) ;
$ratess=$countries."-".$names
?>
<option id="cityoptrates" value="<?php echo $rate; ?>">
<?php echo $ratess; ?>
</option>
<?php
}
}
?>
</select></td>
<td><input name="brkfastchk" type="checkbox" class="chkbox" id="brkfastchk" />
<label for="brkfasttxt"></label>
<input style="background-color:#CCC;" name="brkfasttxt" type="text" id="brkfasttxt" size="5" readonly="readonly" />
<label for="brkfastchk"></label></td>
<td><input type="checkbox" name="lunchchk" id="lunchchk" class="chkbox" />
<label for="lunchtxt"></label>
<input style="background-color:#CCC;" name="lunchtxt" type="text" id="lunchtxt" size="5" readonly="readonly" />
<label for="lunchchk"></label></td>
<td><input type="checkbox" name="dinnerchk" id="dinnerchk" class="chkbox" />
<label for="dinnertxt"></label>
<input style="background-color:#CCC;" name="dinnertxt" type="text" id="dinnertxt" size="5" readonly="readonly" />
<label for="dinnerchk"></label></td>
<td><input type="checkbox" name="incidentlchk" id="incidentlchk" class="chkbox" />
<label for="incidentltxt"></label>
<input style="background-color:#CCC;" name="incidentltxt" type="text" id="incidentltxt" size="5" readonly="readonly" />
<label for="incdntchk"></label></td>
<td colspan="2"><label for="daily_totals"></label>
<input style="background-color:#CCC;" name="daily_totals" type="text" id="daily_totals" size="5" /></td>
</tr>
As per the above my textfield value changing code works perfectly with the first initial row. The cloned rows don't work. The only one which works on the cloned rows is the select menu for selecting the cities. Help needed. Open to suggestions and improvements.
link to actual code in jsfiddle http://jsfiddle.net/NAafu/10/

In your case maybe you should also clone the events:
$('#details').clone(true).appendTo('#dailyexpense');
as stated in the documentation of clone()
EDIT - The problem perhaps is that you are using an id selector ($("#cities").live) which returns only one element. Ids should be unique on the page you should use a class instead

Related

Is there a better way to multiply input values then what I have?

I'm trying to add or multiply input values to come to two total, this was working without trying to use a for loop. My intention was to match the selectors with the various iterations of i that are at the end of each string. I have a fiddle example here : https://jsfiddle.net/shiataz12/Lo1yek2g/69/
I've tried to copy and paste the function while manually inputting names for each iteration, however it doesnt quite work either as only the first two and last two checkbox do anything if clicked.
HTML :
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<<----Assume checkbox --> id --> is $qri and $qri = "qr"."$i";
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr1" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr1"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr1"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr1"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr1" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr1"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot" name="pricef2" value="">
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr2" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr2"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr2"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr2"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr2" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr2"><br><br>
Daily :<span id="dailytotal2"> </span><br><br>
Total :<span id="lengthtotal2"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot2" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot2" name="pricef2" value="">
$(function() {
$("input.quip").change(function() {
$("input.quip").not(this).prop("checked", false);
});
$("input.tent").change(function() {
$("input.tent").not(this).prop("checked", false);
});
$(function() {
//get the values of the selected options
var counter = ("#countrows").val();
var i = 0;
for (i = 1; i <= counter; i++){
let v = $.map($('#qr' + i).is("checked"), function(i) {
return parseFloat($(i).val());
});
let s = v.reduce((a, b) => a + b); //sum them up to a daily total
console.log(v);
$('#dailytotal' + i).text('R' + s + '/day');
$('#lengthtotal' + i).text('R' + s * parseFloat($("#nosday").val()) + '/day');
$('#dailytot' + i).val(s);
$('#lengthtot' + i).val(s * parseFloat($("#nosday").val()));
}
});
});
The example provided assumes that there are two rows of a database and so i = 2 so id's should change to qr2 for i=2. I expected this to work by using the number of rows as a base to use a for in Jquery, limited to the number of rows so that each section can act independently, however they continue to react to the function together and do not show any values.
I thought perhaps if i could get it working for now and copy/paste code with individual id's that'd give me time to work on a better solution however it doesn't work as i'd expected. with map would it be better to declare an array prior and can i use the same id across inputs as an array? It makes calculation easier, although i guess i could use the name selector.
Hopefully someone can guide me to the correct answer, this is driving me up the wall.
Trimmed it down a little. There are other issues. The "Labels for" are suppose to refer to the id of the labelled element. The "Standard" and "Equipped" options are really radio buttons, not checkboxes, since presumably you can have one of the others. I renamed some of the classes and id's, although you may not need all of those. I am presuming that maybe you are generating the HTML dynamically and just add the value of "i" for a suffix, depending upon how many row you have. I actually just made changes to the first row and rewrote the JS to give you a total for the items form the values in the input elements for that row. Not sure exactly how you are calculating those totals, since $("#multiplier") I do not think is even in your code. You will have to look that over and see what you want, but the totals look like it is working.
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="hidden" value = "1.5" id = "multiplier">
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="hidden" value="2" id="countrows"><br><br>
// Assume checkbox is $qri and $qri = "qr"."$i";<br>
<label for="standard1">Standard</label>
<input type="radio" name="equipment" id ="standard1" class="quip qr1" value="125" checked><br><br>
<label for="equipped1">Equipped</label>
<input type="radio" name="equipment" id ="equipped1" class="quip qr1" value="225" ><br><br>
<label for="gps1">GPS</label>
<input type="checkbox" name="gps" id ="gps1" value="20" class ="qr1"><br><br>
<label for="booster1">booster</label>
<input type="checkbox" name="booster" id ="booster1" value="20" class ="qr1"><br><br>
<label for="tents1">One tent</label>
<input type="checkbox" name="tents" id ="tents1" class="tents qr1" value="60" checked><br><br>
<label for="twotents1">Two tents :</label>
<input type="checkbox" name="twotents" id ="twotents1" class="tent qr1" value="80"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
The JS probably needs to be tweaked since I do not know how you are generating the HTML. As it is, it should calculate the totals for all "i" rows on load, and it would not be hard to add something to have it calculate the total for the "ith" row. That should give you something to work with.
function Calc() {
//get the values of the selected options
var counter = $("#countrows").val();
let totals = [];
for (i = 1; i <= counter; i++) {
totals[i] = 0;
$.each($('.qr' + i + ':checked'), function() {
totals[i] += parseInt($(this).val());
});
console.log(totals[i]);
$('#dailytotal' + i).text('R' + totals[i] + '/day');
$('#lengthtotal' + i).text('R' + totals[i] * parseFloat($("#multiplier").val()) + '/day');
$('#dailytot' + i).val(totals[i]);
$('#lengthtot' + i).val(totals[i] * parseFloat($("#multiplier").val()));
}
}
Calc();
$("[class*=qr]").on("change", function(e) {
e.preventDefault();
Calc();
});
"[class*=qr]" isn't the best really because *=qr is not that specific really, depending upon your markup. Also, not clear that you are using form tags anywhere either.

PHP How to Insert Data Input from a Dynamically-Generated Form

I need assistance in taking the next step in inserting data entered into a dynamically-generated form. I have looked for a number of days at other similar questions and am still missing a piece.
Here is my HTML form (minus error trapping/validations):
<form id="form" name="form" method="post" action="recipeaddsubmit.php">
<table id="myTable">
<tr>
<td width="10%">Amount</td>
<td width="10%">Measure</td>
<td width="35%">Ingredient</td>
</tr>
<tr>
<td valign="top">
<input type="text" name="Amt1" id="Amt1" size="1" />
<input type="text" name="Amt2" id="Amt2" size="1" />
</td>
<td valign="top">
<select name="Measure" id="Measure">
<option>Cup</option>
<option>Ounce</option>
</select>
</td>
<td valign="top">
<input type="text" name="Ing" id="Ing" size="40" />
</td>
</tr>
</table>
<button type="button" onclick="displayResult()">Insert new row</button>
<input type="submit" name="button" id="button" value="Submit" />
</form>
Here is the javascript in my header:
<script>
function displayResult()
{
var table=document.getElementById("myTable");
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML="<input type='text' name='Amt1' id='Amt1' size='1' />
<input type='text' name='Amt2' id='Amt2' size='1' />";
cell2.innerHTML="<select name='Measure' id='Measure'> <option>Cup</option>
<option>Ounce</option></select>";
cell3.innerHTML="<input type='text' name='Ing' id='Ing' size='40' />";
}
</script>
And here is my attempted/partial mysqli insert statement (checkInput is a self-created validation function I have used before without issue):
$amt1 = checkInput($_POST['Amt1']);
$amt2 = checkInput($_POST['Amt2']);
$measure = checkInput($_POST['Measure']);
$ing = checkInput($_POST['Ing']);
$ingAddQuery ="INSERT INTO Ingredient (Amt1, Amt2, Measure, Ing)
VALUES ({$amt1}, {$amt2}, {$measure}, {$ing})";
mysqli_query($mysqli,$ingAddQuery);
if (!mysqli_query($mysqli,$ingAddQuery))
{
die('Error: ' . mysqli_error());
}
What I don't understand is how to incorporate a foreach loop in terms of how to increment for a certain number of rows; I understand the concept but not the application in this case.
Thank you for your assistance!
change the name from amt1 to amt1[] and etcetera...
so
<input type="text" name="Amt1[]" id="Amt1[]" size="1" />
When you submit the form,
$_POST['Amt1']; //is an array
will be an array, so you could do
$Amt1Array = $_POST['Amt1'];
foreach($Amt1Array => $Amt1){
//do stuff here
}
Better yet you can index the array using the js to create names like...
<input type="text" name="Amt1[0]" id="Amt1[0]" size="1" />
<input type="text" name="Amt2[0]" id="Amt2[0]" size="1" />
<input type="text" name="Amt1[1]" id="Amt1[1]" size="1" />
<input type="text" name="Amt2[1]" id="Amt2[1]" size="1" />
Then in the PHP you could
$Amt1Array = $_POST['Amt1'];
$Amt2Array = $_POST['Amt2'];
foreach($Amt1Array as $key => $Amt1Value){
$Amt2Value = $Amt2Array[$key];
//do stuff with rows
}
I have a suggestion.
Why don't u create a hidden input type.
<input type="hidden" name="cellCount" value="0" />
Each time u insert a new row, change value of this hidden field. This will not show on browser. This hidden element will also get submit when u submit form. this can be retrieved on server by $_POST["cellCount"].
Hope this will help u.

How can I get value of a text box which is looped using post method to insert value in database?

I had following code.My textbox attend is looped for number of times.I want to get value of each attend when my form is post to insert value in database.
<form method="post" action="insert.php">
<label>Subject</label>
<input type="text" maxlength="30" name="subject" />
<label>Total Lectures</label>
<input type="text" maxlength="30" name="total" />
<table width="537" border="1">
<tr>
<td width="90">Name</td>
<td width="139">Roll Number </td>
<td width="136"> </td>
<td width="144">Attendence</td>
</tr>
<?php
$query=mysql_query("SELECT * FROM STUDENT");
$i=0;
while($rec=mysql_fetch_array($query)){
$i++;
?>
<tr>
<td><?php echo $rec['name']; ?></td>
<td><?php echo $rec['roll_number']; ?></td>
<td> </td>
<td><input type="text" maxlength="10" name="atten" /></td>
</tr>
<?php } ?>
</table>
<input type="submit" value="submit" />
</form>
and my insert.php page is
if($_SERVER['REQUEST_METHOD']=='POST'){
$query=mysql_query("SELECT * FROM STUDENT");
while($rec=mysql_fetch_array($query)){
$attend=$_POST['atten'];
$subject=$_POST['subject'];
$total=$_POST['total'];
$query1=mysql_query("INSERT INTO course VALUES('$i','$subject','$total','$attend','')") or die(mysql_error());
}
}
I am getting only 1 value of text box.
The problem is that you have many inputs all with the name atten. When you post this form, only one of those values will be carried forward.
If you change the name to atten[] all of the values would be posted as an array, which you would then have to loop through to build you insert query.
You could access this posted array as follows:
$attendee_array = $_POST['atten'];
foreach($attendee_array as $attendee) {
// perform insert or build insert query (prefereable as you can do all these inserts at once) here
// make sure to escape your data for input
}
Change the names of your inputs:
<input name="subject[]" value="Lorem" />
<input name="total[]" value="ipsum" />
<input name="atten[]" value="dolor" />
Then:
$_POST['subject'][0] == 'Lorem'
$_POST['total'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an
indefinite amount of information through a form and get it processed
by the server simply by looping through the array of items with the
name "subject". etc.
You need to use input array like:
<input type="text" maxlength="10" name="attend[]" />
And then you will get all the values of attend in an array and you can loop through that $_POST['attend'].

How can I populate a textarea field with various field data from the web form?

We've inherited a php/CodeIgniter app. Without going into all the reasons why, I need to feed values into a textarea field so I can group a bunch of data together and send it to a field in another app/outside vendor. This is the first time we have encountered this issue, but I don't think it is the last, so I want to prepare for it.
The specifics:
Web form with a bunch of fields on it. It's a self generating php/CodeIgniter app that the client controls, so fields are different from client to client.
Certain clients may need to send data from 3, 5, 7, etc., of the field within their form to an external vendor who receives all the data in one field on their end. So in short, using jQuery, I want to send data from certain fields to a textarea field.
For example, I want to send Center Title, Full Name, and Fruits to the textarea field with a line break at the end of each. Of course, if the user empties a field, that line item would be removed from the textarea field.
Click here to view my jsFiddle demo.
HTML Example:
<form method="post">
<br />
<br />
<fieldset name="Group1" style="border: thin; border-color: green">
<legend>General Information</legend>
<table style="width: 100%">
<tr>
<td style="width: 249px">Center Title:</td>
<td>
<select name="centers" id="centers">
<option value="Corp 1">Corp 1</option>
<option value="Shamrock Gold">Shamrock Gold</option>
<option value="Hensin Way">Hensin Way</option>
</select>
</td>
</tr>
<tr>
<td style="width: 249px">Full Name:</td>
<td>
<input name="fullname" id="fullname" type="text" size="20" />
</td>
</tr>
<tr>
<td style="width: 249px">Job Title:</td>
<td>
<input name="jobtitle" id="jobtitle" type="text" />
</td>
</tr>
<tr>
<td style="width: 249px">Known Alergies:</td>
<td>
<input name="knownAllergies" id="knownAllergies" type="checkbox" value="Yes" />Yes
<input name="knownAllergies" id="knownAllergies" type="checkbox" value="No" />No
</td>
</tr>
<tr>
<td style="width: 249px; height: 102px;">How Many?:</td>
<td style="height: 102px">
<select multiple="multiple" name="Select2">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
</td>
</tr>
<tr>
<td style="width: 249px">Fruits:</td>
<td>
<input name="Fruit[]" id="Fruit[]" type="radio" checked="checked" value="Apple" />Apple<br />
<input name="Fruit[]" id="Fruit[]" type="radio" value="Orange" />Orange<br />
<input name="Fruit[]" id="Fruit[]" type="radio" value="Fruit" />Fruit
</td>
</tr>
</table>
<label>Complete Info:</label>
<textarea name="allVendorInfo" id="allVendorInfo" cols="50" rows="7"></textarea><br />
<br />
</fieldset>
</form>
​
You can access selections/user-input using following code
$(document).ready(function(){
$("input").change(function(e){
if($(this).is(':checked')){
}else{
};
var old = $('#allVendorInfo').val();
$('#allVendorInfo').val(old+ "%" + $(this).attr('name') + '|'+$(this).val() + "%");
});
$("select").change(function(e){
var old = $('#allVendorInfo').val();
$('#allVendorInfo').val(old+ "%" + $(this).attr('name') + '|'+$(this).val() + "%");
});
});​
EDIT: Original fiddle was broken for some reason, have updated the link
I was thinking something along the lines of this: http://jsfiddle.net/JRwzz/3/
The 'trigger' for this could be something other than the Run JS button of course, that's just there for example, i'd imagine it'd be on submit or other user action.
It clears the textarea first, then loops all of the input's and selects, depending on the type of element - checkbox, radio, select etc.. it uses slightly different methods to get the values (e.g. if it's a checkbox it only wants to get the value from a checked one)
It'll need a bit of polish in order to have a checkbox group's values all on one line and things like that, but hopefully this is enough for you to get the idea.
Then on each thing it finds it appends it to the textarea and puts a linebreak on the end.
It wouldn't be too hard to add a condition to check for another atribute (e.g. data-export="yes") to check for before including it in the textarea.
Just to note, I thought of it this way because you said all of the forms are dynamic, so I tried not to need to rely on ID's or names for things, it'll just apply to any form. If you can get the code that generates your forms to output an attribute in the html on the ones you want included in your textarea (and perhaps some method of your client selecting which ones that'll apply to in their administration area) then that'd be spot on, would save having to fiddle JS for every client.
Try something like this:
$("select, input").bind("change keyup", function() {
var form = $("<form>");
var data = new Object();
form.append($(":checked").clone());
$.each($("select"), function(i, item) {
if ($(item).val() != null) {
form.append(($(item).clone()));
}
});
$.each($("input[type='text']"), function(i, item) {
if ($(item).val().length > 0) form.append(($(item).clone()));
});
$("#allVendorInfo").val(form.serialize());
}).first().trigger("change");​

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